enact-context 0.0.2

Context window management and compaction for Enact
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
//! Context Compaction
//!
//! Strategies for reducing context size when approaching limits.
//!
//! @see packages/enact-schemas/src/context.schemas.ts

use crate::segment::{ContextPriority, ContextSegment, ContextSegmentType};
use chrono::{DateTime, Utc};
use enact_core::kernel::ExecutionId;
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// Compaction errors
#[derive(Debug, Error)]
pub enum CompactionError {
    #[error("Nothing to compact")]
    NothingToCompact,

    #[error("Target token count too low: {0}")]
    TargetTooLow(usize),

    #[error("Summarization failed: {0}")]
    SummarizationFailed(String),
}

/// Available compaction strategies
///
/// Matches `compactionStrategyTypeSchema` in @enact/schemas
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CompactionStrategyType {
    /// Simple truncation (remove oldest)
    Truncate,
    /// LLM summarization
    Summarize,
    /// Extract key points only
    ExtractKeyPoints,
    /// Keep only recent N messages
    SlidingWindow,
    /// Keep based on importance scores
    ImportanceWeighted,
    /// Combination of strategies
    Hybrid,
}

/// Configuration for context compaction
///
/// Matches `compactionStrategySchema` in @enact/schemas
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CompactionStrategy {
    /// Strategy type
    #[serde(rename = "type")]
    pub strategy_type: CompactionStrategyType,

    /// Target token count after compaction
    pub target_tokens: usize,

    /// Minimum content to preserve (percentage, 0-100)
    pub min_preserve_percent: u8,

    /// Segments to compact (in priority order)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub segments_to_compact: Option<Vec<ContextSegmentType>>,

    /// Segments to never compact
    #[serde(skip_serializing_if = "Option::is_none")]
    pub protected_segments: Option<Vec<ContextSegmentType>>,

    /// For summarize strategy: max summary tokens
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary_max_tokens: Option<usize>,

    /// For sliding_window strategy: window size
    #[serde(skip_serializing_if = "Option::is_none")]
    pub window_size: Option<usize>,

    /// For importance_weighted: minimum importance score to keep
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_importance_score: Option<f64>,
}

impl CompactionStrategy {
    /// Create a truncation strategy
    pub fn truncate(target_tokens: usize) -> Self {
        Self {
            strategy_type: CompactionStrategyType::Truncate,
            target_tokens,
            min_preserve_percent: 20,
            segments_to_compact: None,
            protected_segments: Some(vec![
                ContextSegmentType::System,
                ContextSegmentType::UserInput,
            ]),
            summary_max_tokens: None,
            window_size: None,
            min_importance_score: None,
        }
    }

    /// Create a sliding window strategy
    pub fn sliding_window(target_tokens: usize, window_size: usize) -> Self {
        Self {
            strategy_type: CompactionStrategyType::SlidingWindow,
            target_tokens,
            min_preserve_percent: 20,
            segments_to_compact: Some(vec![ContextSegmentType::History]),
            protected_segments: Some(vec![
                ContextSegmentType::System,
                ContextSegmentType::UserInput,
            ]),
            summary_max_tokens: None,
            window_size: Some(window_size),
            min_importance_score: None,
        }
    }

    /// Create a summarization strategy
    pub fn summarize(target_tokens: usize, summary_max_tokens: usize) -> Self {
        Self {
            strategy_type: CompactionStrategyType::Summarize,
            target_tokens,
            min_preserve_percent: 30,
            segments_to_compact: Some(vec![
                ContextSegmentType::History,
                ContextSegmentType::ToolResults,
            ]),
            protected_segments: Some(vec![
                ContextSegmentType::System,
                ContextSegmentType::UserInput,
                ContextSegmentType::Guidance,
            ]),
            summary_max_tokens: Some(summary_max_tokens),
            window_size: None,
            min_importance_score: None,
        }
    }

    /// Check if a segment type is protected
    pub fn is_protected(&self, segment_type: ContextSegmentType) -> bool {
        self.protected_segments
            .as_ref()
            .map(|p| p.contains(&segment_type))
            .unwrap_or(false)
    }

    /// Check if a segment type should be compacted
    pub fn should_compact(&self, segment_type: ContextSegmentType) -> bool {
        if self.is_protected(segment_type) {
            return false;
        }

        self.segments_to_compact
            .as_ref()
            .map(|s| s.contains(&segment_type))
            .unwrap_or(true) // If not specified, compact all non-protected
    }
}

/// Result of a compaction operation
///
/// Matches `compactionResultSchema` in @enact/schemas
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CompactionResult {
    /// Execution ID
    pub execution_id: ExecutionId,

    /// Strategy used
    pub strategy: CompactionStrategyType,

    /// Tokens before compaction
    pub tokens_before: usize,

    /// Tokens after compaction
    pub tokens_after: usize,

    /// Tokens saved
    pub tokens_saved: usize,

    /// Compression ratio (tokensAfter / tokensBefore)
    pub compression_ratio: f64,

    /// Number of segments compacted
    pub segments_compacted: usize,

    /// Duration in milliseconds
    pub duration_ms: u64,

    /// Whether compaction was successful
    pub success: bool,

    /// Error message if failed
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,

    /// Timestamp
    pub compacted_at: DateTime<Utc>,
}

impl CompactionResult {
    /// Create a successful result
    pub fn success(
        execution_id: ExecutionId,
        strategy: CompactionStrategyType,
        tokens_before: usize,
        tokens_after: usize,
        segments_compacted: usize,
        duration_ms: u64,
    ) -> Self {
        let tokens_saved = tokens_before.saturating_sub(tokens_after);
        let compression_ratio = if tokens_before > 0 {
            tokens_after as f64 / tokens_before as f64
        } else {
            1.0
        };

        Self {
            execution_id,
            strategy,
            tokens_before,
            tokens_after,
            tokens_saved,
            compression_ratio,
            segments_compacted,
            duration_ms,
            success: true,
            error: None,
            compacted_at: Utc::now(),
        }
    }

    /// Create a failed result
    pub fn failure(
        execution_id: ExecutionId,
        strategy: CompactionStrategyType,
        tokens_before: usize,
        error: String,
        duration_ms: u64,
    ) -> Self {
        Self {
            execution_id,
            strategy,
            tokens_before,
            tokens_after: tokens_before,
            tokens_saved: 0,
            compression_ratio: 1.0,
            segments_compacted: 0,
            duration_ms,
            success: false,
            error: Some(error),
            compacted_at: Utc::now(),
        }
    }
}

/// Compactor - applies compaction strategies to segments
pub struct Compactor {
    strategy: CompactionStrategy,
}

impl Compactor {
    /// Create a new compactor with the given strategy
    pub fn new(strategy: CompactionStrategy) -> Self {
        Self { strategy }
    }

    /// Create a truncation compactor
    pub fn truncate(target_tokens: usize) -> Self {
        Self::new(CompactionStrategy::truncate(target_tokens))
    }

    /// Create a sliding window compactor
    pub fn sliding_window(target_tokens: usize, window_size: usize) -> Self {
        Self::new(CompactionStrategy::sliding_window(
            target_tokens,
            window_size,
        ))
    }

    /// Get the strategy
    pub fn strategy(&self) -> &CompactionStrategy {
        &self.strategy
    }

    /// Compact segments using truncation strategy
    ///
    /// Removes oldest segments (lowest priority first) until target is reached.
    pub fn compact_truncate(
        &self,
        segments: &mut Vec<ContextSegment>,
        current_tokens: usize,
    ) -> Result<usize, CompactionError> {
        if current_tokens <= self.strategy.target_tokens {
            return Ok(0);
        }

        let tokens_to_remove = current_tokens - self.strategy.target_tokens;
        let mut removed = 0;

        // Sort by priority (ascending) then by sequence (ascending = oldest first)
        segments.sort_by(|a, b| {
            a.priority
                .cmp(&b.priority)
                .then(a.sequence.cmp(&b.sequence))
        });

        // Remove lowest priority, oldest segments first
        let mut i = 0;
        while i < segments.len() && removed < tokens_to_remove {
            let segment = &segments[i];

            // Skip protected segments
            if !segment.compressible || self.strategy.is_protected(segment.segment_type) {
                i += 1;
                continue;
            }

            // Skip critical priority
            if segment.priority == ContextPriority::Critical {
                i += 1;
                continue;
            }

            removed += segment.token_count;
            segments.remove(i);
        }

        Ok(removed)
    }

    /// Compact using sliding window strategy
    ///
    /// Keeps only the most recent N messages in the history.
    pub fn compact_sliding_window(
        &self,
        segments: &mut Vec<ContextSegment>,
    ) -> Result<usize, CompactionError> {
        let window_size = self.strategy.window_size.unwrap_or(10);

        // Find history segments
        let history_indices: Vec<usize> = segments
            .iter()
            .enumerate()
            .filter(|(_, s)| s.segment_type == ContextSegmentType::History)
            .map(|(i, _)| i)
            .collect();

        if history_indices.len() <= window_size {
            return Ok(0);
        }

        // Remove oldest history segments (keep window_size most recent)
        let to_remove = history_indices.len() - window_size;
        let mut removed_tokens = 0;

        // Remove from oldest first (indices are in ascending order)
        for &idx in history_indices.iter().take(to_remove).rev() {
            removed_tokens += segments[idx].token_count;
            segments.remove(idx);
        }

        Ok(removed_tokens)
    }

    /// Create a summarize compactor
    pub fn summarize(target_tokens: usize, summary_max_tokens: usize) -> Self {
        Self::new(CompactionStrategy::summarize(
            target_tokens,
            summary_max_tokens,
        ))
    }

    /// Compact using summarization strategy
    ///
    /// This performs extractive summarization by:
    /// 1. Identifying compactible segments (History, ToolResults)
    /// 2. Extracting key sentences from each segment
    /// 3. Truncating to fit within the summary token budget
    ///
    /// Note: For true abstractive summarization (using an LLM), integrate with
    /// an external summarization service. This implementation provides a local
    /// extractive approach that doesn't require external API calls.
    pub fn compact_summarize(
        &self,
        segments: &mut Vec<ContextSegment>,
        current_tokens: usize,
    ) -> Result<usize, CompactionError> {
        if current_tokens <= self.strategy.target_tokens {
            return Ok(0);
        }

        let summary_max = self.strategy.summary_max_tokens.unwrap_or(500);
        let mut removed_tokens = 0;

        // Get segments that should be compacted
        let segments_to_compact = self
            .strategy
            .segments_to_compact
            .clone()
            .unwrap_or_else(|| vec![ContextSegmentType::History, ContextSegmentType::ToolResults]);

        // Process each segment type
        for segment_type in segments_to_compact {
            // Find segments of this type that can be compacted
            let mut indices_to_summarize: Vec<usize> = Vec::new();
            let mut combined_content = String::new();
            let mut total_tokens_in_group = 0;

            for (i, segment) in segments.iter().enumerate() {
                if segment.segment_type == segment_type
                    && segment.compressible
                    && !self.strategy.is_protected(segment.segment_type)
                    && segment.priority != ContextPriority::Critical
                {
                    indices_to_summarize.push(i);
                    if !combined_content.is_empty() {
                        combined_content.push_str("\n---\n");
                    }
                    combined_content.push_str(&segment.content);
                    total_tokens_in_group += segment.token_count;
                }
            }

            // Skip if nothing to summarize or if summarizing would save no tokens
            if indices_to_summarize.is_empty() || total_tokens_in_group <= summary_max {
                continue;
            }

            // Extract key sentences (extractive summarization)
            let summary = self.extract_key_content(&combined_content, summary_max);
            let summary_tokens = summary.len() / 4; // Rough token estimate (will be recounted)

            // Remove old segments (in reverse order to preserve indices)
            for &idx in indices_to_summarize.iter().rev() {
                removed_tokens += segments[idx].token_count;
                segments.remove(idx);
            }

            // Add summarized segment if there's content
            if !summary.is_empty() {
                let summarized_segment = ContextSegment::new(
                    segment_type,
                    format!(
                        "[Summarized {}]\n{}",
                        segment_type_display(segment_type),
                        summary
                    ),
                    summary_tokens,
                    0, // Sequence will be updated by ContextWindow
                )
                .with_priority(ContextPriority::Low);

                segments.push(summarized_segment);
                removed_tokens = removed_tokens.saturating_sub(summary_tokens);
            }
        }

        if removed_tokens == 0 {
            return Err(CompactionError::NothingToCompact);
        }

        Ok(removed_tokens)
    }

    /// Extract key content from text using extractive summarization
    ///
    /// Uses heuristics to identify important sentences:
    /// - First and last sentences (often contain key info)
    /// - Sentences with important keywords
    /// - Sentences with certain patterns (results, conclusions, errors)
    fn extract_key_content(&self, text: &str, max_tokens: usize) -> String {
        let sentences: Vec<&str> = text
            .split(&['.', '!', '?', '\n'][..])
            .map(|s| s.trim())
            .filter(|s| !s.is_empty() && s.len() > 10)
            .collect();

        if sentences.is_empty() {
            return String::new();
        }

        // Score sentences by importance
        let mut scored_sentences: Vec<(usize, &str, i32)> = sentences
            .iter()
            .enumerate()
            .map(|(i, &s)| (i, s, self.score_sentence(s, i, sentences.len())))
            .collect();

        // Sort by score (descending)
        scored_sentences.sort_by(|a, b| b.2.cmp(&a.2));

        // Build summary within token budget
        let max_chars = max_tokens * 4; // Rough estimate: ~4 chars per token
        let mut summary_parts: Vec<(usize, &str)> = Vec::new();
        let mut current_len = 0;

        for (idx, sentence, _score) in scored_sentences {
            if current_len + sentence.len() + 2 > max_chars {
                break;
            }
            summary_parts.push((idx, sentence));
            current_len += sentence.len() + 2;
        }

        // Sort by original position to maintain coherence
        summary_parts.sort_by_key(|(idx, _)| *idx);

        // Join sentences
        summary_parts
            .iter()
            .map(|(_, s)| *s)
            .collect::<Vec<_>>()
            .join(". ")
            + "."
    }

    /// Score a sentence for importance (higher = more important)
    fn score_sentence(&self, sentence: &str, position: usize, total: usize) -> i32 {
        let mut score = 0i32;
        let lower = sentence.to_lowercase();

        // Position-based scoring
        if position == 0 {
            score += 10; // First sentence often important
        }
        if position == total - 1 {
            score += 8; // Last sentence often contains conclusion
        }

        // Keyword-based scoring
        let important_keywords = [
            ("result", 5),
            ("output", 4),
            ("error", 6),
            ("success", 5),
            ("fail", 6),
            ("complete", 4),
            ("return", 3),
            ("created", 3),
            ("found", 3),
            ("important", 4),
            ("note", 3),
            ("warning", 5),
            ("summary", 4),
            ("conclusion", 5),
            ("decision", 4),
            ("because", 3),
            ("therefore", 3),
        ];

        for (keyword, keyword_score) in important_keywords {
            if lower.contains(keyword) {
                score += keyword_score;
            }
        }

        // Length penalty for very short or very long sentences
        let len = sentence.len();
        if len < 20 {
            score -= 2;
        } else if len > 200 {
            score -= 1;
        }

        // Bonus for sentences with code/technical content
        if sentence.contains('`') || sentence.contains("()") || sentence.contains("::") {
            score += 2;
        }

        score
    }

    /// Compact using key points extraction strategy (not yet implemented)
    ///
    /// # Future Implementation
    ///
    /// This strategy would:
    /// 1. Identify key decision points, outcomes, and learnings
    /// 2. Extract structured bullet points from conversation
    /// 3. Preserve causal chains and reasoning
    ///
    /// Requires integration with an LLM for semantic understanding.
    pub fn compact_extract_key_points(
        &self,
        _segments: &mut Vec<ContextSegment>,
        _current_tokens: usize,
    ) -> Result<usize, CompactionError> {
        Err(CompactionError::SummarizationFailed(
            "ExtractKeyPoints strategy is not yet implemented. \
            This strategy requires LLM integration for semantic key point extraction. \
            Consider using 'Summarize' for extractive summarization or \
            'SlidingWindow' for recency-based compaction."
                .to_string(),
        ))
    }

    /// Compact using importance-weighted strategy (not yet implemented)
    ///
    /// # Future Implementation
    ///
    /// This strategy would:
    /// 1. Score each segment based on semantic importance
    /// 2. Use embedding similarity to current task
    /// 3. Weight by recency, reference count, and explicit importance markers
    /// 4. Remove lowest-scored segments until target is reached
    ///
    /// Requires embedding model integration for semantic scoring.
    pub fn compact_importance_weighted(
        &self,
        _segments: &mut Vec<ContextSegment>,
        _current_tokens: usize,
    ) -> Result<usize, CompactionError> {
        Err(CompactionError::SummarizationFailed(
            "ImportanceWeighted strategy is not yet implemented. \
            This strategy requires embedding model integration for semantic importance scoring. \
            Consider using 'Truncate' for priority-based removal or \
            'SlidingWindow' for recency-based compaction."
                .to_string(),
        ))
    }

    /// Compact using hybrid strategy (not yet implemented)
    ///
    /// # Future Implementation
    ///
    /// This strategy would combine multiple approaches:
    /// 1. First pass: Remove lowest-importance segments (truncate)
    /// 2. Second pass: Summarize remaining compressible content
    /// 3. Third pass: Apply sliding window to history if needed
    ///
    /// Requires all component strategies to be implemented.
    pub fn compact_hybrid(
        &self,
        _segments: &mut Vec<ContextSegment>,
        _current_tokens: usize,
    ) -> Result<usize, CompactionError> {
        Err(CompactionError::SummarizationFailed(
            "Hybrid strategy is not yet implemented. \
            This strategy combines multiple compaction approaches for optimal results. \
            Consider using individual strategies: 'Summarize', 'Truncate', or 'SlidingWindow'."
                .to_string(),
        ))
    }
}

/// Display name for segment types in summaries
fn segment_type_display(segment_type: ContextSegmentType) -> &'static str {
    match segment_type {
        ContextSegmentType::System => "System",
        ContextSegmentType::History => "Conversation History",
        ContextSegmentType::WorkingMemory => "Working Memory",
        ContextSegmentType::ToolResults => "Tool Results",
        ContextSegmentType::RagContext => "Retrieved Context",
        ContextSegmentType::UserInput => "User Input",
        ContextSegmentType::AgentScratchpad => "Agent Notes",
        ContextSegmentType::ChildSummary => "Child Execution",
        ContextSegmentType::Guidance => "Guidance",
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_truncation_strategy() {
        let strategy = CompactionStrategy::truncate(1000);
        assert_eq!(strategy.strategy_type, CompactionStrategyType::Truncate);
        assert!(strategy.is_protected(ContextSegmentType::System));
        assert!(!strategy.is_protected(ContextSegmentType::History));
    }

    #[test]
    fn test_compaction_result() {
        let exec_id = ExecutionId::new();
        let result = CompactionResult::success(
            exec_id,
            CompactionStrategyType::Truncate,
            10000,
            5000,
            5,
            100,
        );

        assert!(result.success);
        assert_eq!(result.tokens_saved, 5000);
        assert!((result.compression_ratio - 0.5).abs() < 0.01);
    }

    #[test]
    fn test_summarize_strategy_creation() {
        let strategy = CompactionStrategy::summarize(5000, 500);
        assert_eq!(strategy.strategy_type, CompactionStrategyType::Summarize);
        assert_eq!(strategy.target_tokens, 5000);
        assert_eq!(strategy.summary_max_tokens, Some(500));
        assert!(strategy.is_protected(ContextSegmentType::System));
        assert!(strategy.is_protected(ContextSegmentType::UserInput));
        assert!(!strategy.is_protected(ContextSegmentType::History));
    }

    #[test]
    fn test_summarize_compactor_creation() {
        let compactor = Compactor::summarize(5000, 500);
        assert_eq!(
            compactor.strategy().strategy_type,
            CompactionStrategyType::Summarize
        );
    }

    #[test]
    fn test_compact_summarize_no_change_under_target() {
        let compactor = Compactor::summarize(10000, 500);
        let mut segments = vec![ContextSegment::history(
            "Some history content here.",
            100,
            1,
        )];

        // Current tokens (100) is under target (10000), so no compaction
        let result = compactor.compact_summarize(&mut segments, 100);
        assert_eq!(result.unwrap(), 0);
        assert_eq!(segments.len(), 1);
    }

    #[test]
    fn test_compact_summarize_with_history() {
        let compactor = Compactor::summarize(500, 100);
        let mut segments = vec![
            ContextSegment::system("You are a helpful assistant.", 10),
            ContextSegment::history(
                "The user asked about Rust programming. We discussed memory safety and ownership. \
                The result was a successful explanation. The conclusion is that Rust is great.",
                800,
                1,
            ),
            ContextSegment::history(
                "Then we talked about error handling. The important point is that Result types are used. \
                This is a note about the discussion. The output showed various patterns.",
                700,
                2,
            ),
        ];

        let current_tokens = 10 + 800 + 700;
        let result = compactor.compact_summarize(&mut segments, current_tokens);

        assert!(result.is_ok());
        let removed = result.unwrap();
        assert!(removed > 0, "Should have removed some tokens");

        // System segment should be preserved
        assert!(segments
            .iter()
            .any(|s| s.segment_type == ContextSegmentType::System));

        // Should have a summarized history segment
        let summarized = segments
            .iter()
            .find(|s| s.segment_type == ContextSegmentType::History);
        assert!(summarized.is_some());
        assert!(summarized.unwrap().content.contains("[Summarized"));
    }

    #[test]
    fn test_compact_summarize_preserves_protected() {
        let compactor = Compactor::summarize(100, 50);
        let mut segments = vec![
            ContextSegment::system("System prompt", 20),
            ContextSegment::user_input("User question", 15, 1),
            ContextSegment::guidance("Important guidance", 25, 2),
            ContextSegment::history("Some history that can be compressed.", 500, 3),
        ];

        let current_tokens = 20 + 15 + 25 + 500;
        let _ = compactor.compact_summarize(&mut segments, current_tokens);

        // Protected segments should still exist
        assert!(segments
            .iter()
            .any(|s| s.segment_type == ContextSegmentType::System));
        assert!(segments
            .iter()
            .any(|s| s.segment_type == ContextSegmentType::UserInput));
        assert!(segments
            .iter()
            .any(|s| s.segment_type == ContextSegmentType::Guidance));
    }

    #[test]
    fn test_extract_key_content_prioritizes_important_sentences() {
        let compactor = Compactor::summarize(5000, 100);

        // Create a longer text where summarization will actually reduce content
        let text = "This is the first sentence and sets context for the discussion. \
            Some filler information here that is not particularly important. \
            Another sentence with no real significance to the outcome. \
            The result of the operation was successful and completed without errors. \
            More random content follows that could be removed. \
            Yet another sentence that adds little value to understanding. \
            Some additional padding content here. \
            In conclusion, this is the summary of our findings.";

        // Use a small token limit to force extraction
        let summary = compactor.extract_key_content(text, 20);

        // Should prioritize first sentence, result sentence, and conclusion
        assert!(!summary.is_empty());
        // With only 20 tokens (~80 chars), summary should be shorter than original
        assert!(
            summary.len() < text.len(),
            "Summary ({} chars) should be shorter than original ({} chars)",
            summary.len(),
            text.len()
        );
    }

    #[test]
    fn test_extract_key_content_handles_empty() {
        let compactor = Compactor::summarize(5000, 100);
        let summary = compactor.extract_key_content("", 50);
        assert!(summary.is_empty() || summary == ".");
    }

    #[test]
    fn test_score_sentence_keywords() {
        let compactor = Compactor::summarize(5000, 100);

        let error_sentence = "There was an error in the process";
        let normal_sentence = "The weather is nice today";

        let error_score = compactor.score_sentence(error_sentence, 1, 5);
        let normal_score = compactor.score_sentence(normal_sentence, 1, 5);

        assert!(
            error_score > normal_score,
            "Error sentence should score higher"
        );
    }

    #[test]
    fn test_score_sentence_position() {
        let compactor = Compactor::summarize(5000, 100);
        let sentence = "This is a test sentence";

        let first_score = compactor.score_sentence(sentence, 0, 5);
        let middle_score = compactor.score_sentence(sentence, 2, 5);
        let last_score = compactor.score_sentence(sentence, 4, 5);

        assert!(
            first_score > middle_score,
            "First sentence should score higher"
        );
        assert!(
            last_score > middle_score,
            "Last sentence should score higher"
        );
    }

    #[test]
    fn test_extract_key_points_not_implemented() {
        let strategy = CompactionStrategy {
            strategy_type: CompactionStrategyType::ExtractKeyPoints,
            target_tokens: 5000,
            min_preserve_percent: 20,
            segments_to_compact: None,
            protected_segments: None,
            summary_max_tokens: None,
            window_size: None,
            min_importance_score: None,
        };
        let compactor = Compactor::new(strategy);
        let mut segments = vec![];

        let result = compactor.compact_extract_key_points(&mut segments, 1000);
        assert!(result.is_err());

        let err = result.unwrap_err();
        match err {
            CompactionError::SummarizationFailed(msg) => {
                assert!(msg.contains("ExtractKeyPoints"));
                assert!(msg.contains("not yet implemented"));
            }
            _ => panic!("Expected SummarizationFailed error"),
        }
    }

    #[test]
    fn test_importance_weighted_not_implemented() {
        let strategy = CompactionStrategy {
            strategy_type: CompactionStrategyType::ImportanceWeighted,
            target_tokens: 5000,
            min_preserve_percent: 20,
            segments_to_compact: None,
            protected_segments: None,
            summary_max_tokens: None,
            window_size: None,
            min_importance_score: Some(0.5),
        };
        let compactor = Compactor::new(strategy);
        let mut segments = vec![];

        let result = compactor.compact_importance_weighted(&mut segments, 1000);
        assert!(result.is_err());

        let err = result.unwrap_err();
        match err {
            CompactionError::SummarizationFailed(msg) => {
                assert!(msg.contains("ImportanceWeighted"));
                assert!(msg.contains("not yet implemented"));
                assert!(msg.contains("embedding model"));
            }
            _ => panic!("Expected SummarizationFailed error"),
        }
    }

    #[test]
    fn test_hybrid_not_implemented() {
        let strategy = CompactionStrategy {
            strategy_type: CompactionStrategyType::Hybrid,
            target_tokens: 5000,
            min_preserve_percent: 20,
            segments_to_compact: None,
            protected_segments: None,
            summary_max_tokens: None,
            window_size: None,
            min_importance_score: None,
        };
        let compactor = Compactor::new(strategy);
        let mut segments = vec![];

        let result = compactor.compact_hybrid(&mut segments, 1000);
        assert!(result.is_err());

        let err = result.unwrap_err();
        match err {
            CompactionError::SummarizationFailed(msg) => {
                assert!(msg.contains("Hybrid"));
                assert!(msg.contains("not yet implemented"));
            }
            _ => panic!("Expected SummarizationFailed error"),
        }
    }

    #[test]
    fn test_segment_type_display() {
        assert_eq!(
            segment_type_display(ContextSegmentType::History),
            "Conversation History"
        );
        assert_eq!(
            segment_type_display(ContextSegmentType::ToolResults),
            "Tool Results"
        );
        assert_eq!(segment_type_display(ContextSegmentType::System), "System");
    }
}