Skip to main content

agent_base/engine/
context.rs

1use crate::types::{ChatMessage, SessionId};
2
3/// Find the first non-ephemeral System message (the system prompt).
4pub fn first_system_prompt(messages: &[ChatMessage]) -> Option<ChatMessage> {
5    messages.iter().find_map(|msg| match msg {
6        ChatMessage::System {
7            content,
8            ephemeral: false,
9        } => Some(ChatMessage::system(content.clone())),
10        _ => None,
11    })
12}
13
14/// Estimate total tokens across a message list using `ContextWindowManager::message_tokens`.
15pub fn estimate_messages_tokens(messages: &[ChatMessage]) -> usize {
16    messages
17        .iter()
18        .map(ContextWindowManager::message_tokens)
19        .sum()
20}
21
22// ── Context Window Manager ──────────────────────────────────────────────────
23
24#[derive(Clone, Debug)]
25pub struct ContextWindowManager {
26    pub max_tokens: usize,
27    /// Always keep first N messages (typically system prompt)
28    pub keep_first_n: usize,
29    /// Always keep last N messages
30    pub keep_last_n: usize,
31}
32
33impl Default for ContextWindowManager {
34    fn default() -> Self {
35        Self {
36            max_tokens: 128_000,
37            keep_first_n: 1,
38            keep_last_n: 20,
39        }
40    }
41}
42
43impl ContextWindowManager {
44    /// OpenAI Vision API fixed token overhead per image
45    const IMAGE_OVERHEAD_TOKENS: usize = 85;
46
47    /// Vision pricing: ~750 pixels per token at high detail — the magnitude
48    /// every provider's image bill lives in. The estimator prices the
49    /// picture as the WIRE sends it (shrunk to `MAX_WIRE_LONG_EDGE`), never
50    /// the session's stored original.
51    ///
52    /// The old estimator priced the base64 payload as text (`data.len() / 4`),
53    /// which billed one 1278x1152 screenshot at ~219k tokens instead of ~2k.
54    /// Two pasted screenshots then tripped the `max_message_tokens` safety
55    /// valve, the valve popped the whole user message, and the turn went out
56    /// with an empty message list (session 20261108_c525b6c7).
57    const IMAGE_PIXELS_PER_TOKEN: u64 = 750;
58
59    /// Price for an attachment whose header cannot be read (exotic format,
60    /// corrupt payload, not an image at all): the worst case the wire budget
61    /// lets through — a downscaled 1568x1568 picture is ~3.3k tokens — so an
62    /// unreadable payload is never underpriced into the request.
63    const IMAGE_UNREADABLE_TOKENS: usize = 3_500;
64
65    pub fn new(max_tokens: usize) -> Self {
66        Self {
67            max_tokens,
68            ..Default::default()
69        }
70    }
71
72    pub fn with_keep_first_n(mut self, n: usize) -> Self {
73        self.keep_first_n = n;
74        self
75    }
76
77    pub fn with_keep_last_n(mut self, n: usize) -> Self {
78        self.keep_last_n = n;
79        self
80    }
81
82    /// Simple token estimation: ~4 chars/token for Latin, ~1.5 for CJK
83    /// Mixed text uses a compromise of 3 chars/token
84    pub fn estimate_tokens(text: &str) -> usize {
85        if text.is_empty() {
86            return 0;
87        }
88        let chars = text.chars().count();
89        let cjk_count = text.chars().filter(|c| is_cjk(*c)).count();
90        let latin_count = chars - cjk_count;
91        // CJK: ~1.5 chars/token, Latin: ~4 chars/token
92        (cjk_count as f64 / 1.5 + latin_count as f64 / 4.0).ceil() as usize
93    }
94
95    /// What one picture costs — fixed overhead plus either its wire-scale
96    /// pixel count (a base64 payload whose header reads), the URL text (a
97    /// reference the provider fetches), or the capped fallback.
98    fn image_tokens(image: &crate::types::ImageAttachment) -> usize {
99        use crate::types::ImageAttachment;
100        let body = match image {
101            ImageAttachment::Url { url, detail: _ } => Self::estimate_tokens(url),
102            ImageAttachment::Base64 {
103                data,
104                media_type,
105                detail: _,
106            } => {
107                let mut tokens = match crate::image_ops::base64_prefix_dims(data) {
108                    Some((w, h)) => Self::pixel_tokens(w, h),
109                    None => Self::IMAGE_UNREADABLE_TOKENS,
110                };
111                if let Some(mt) = media_type {
112                    tokens += Self::estimate_tokens(mt);
113                }
114                tokens
115            }
116        };
117        body + Self::IMAGE_OVERHEAD_TOKENS
118    }
119
120    /// Pixel price of a picture as it travels: the wire shrinks any long
121    /// edge above the cap, so price the scaled pixels — never more than a
122    /// full-cap picture.
123    fn pixel_tokens(w: u32, h: u32) -> usize {
124        let long = u64::from(w.max(h)).max(1);
125        let cap = u64::from(crate::image_ops::MAX_WIRE_LONG_EDGE);
126        let (w, h) = if long > cap {
127            (u64::from(w) * cap / long, u64::from(h) * cap / long)
128        } else {
129            (u64::from(w), u64::from(h))
130        };
131        let pixels = (w * h).max(1);
132        (pixels.div_ceil(Self::IMAGE_PIXELS_PER_TOKEN)) as usize
133    }
134
135    /// Estimate a user message's tokens from its parts — the turn-entry size
136    /// gate uses it before the message exists as a [`ChatMessage`].
137    pub(crate) fn user_message_tokens(
138        content: &str,
139        images: &[crate::types::ImageAttachment],
140    ) -> usize {
141        Self::estimate_tokens(content) + images.iter().map(Self::image_tokens).sum::<usize>()
142    }
143
144    pub(crate) fn message_tokens(msg: &ChatMessage) -> usize {
145        match msg {
146            ChatMessage::System { content, .. } => Self::estimate_tokens(content),
147            ChatMessage::User {
148                content, images, ..
149            } => Self::user_message_tokens(content, images),
150            ChatMessage::Assistant {
151                content,
152                reasoning_content,
153                tool_calls,
154                thinking_signature: _,
155            } => {
156                let mut tokens = content.as_deref().map(Self::estimate_tokens).unwrap_or(0);
157                if let Some(rc) = reasoning_content {
158                    tokens += Self::estimate_tokens(rc);
159                }
160                if let Some(tc) = tool_calls {
161                    for t in tc {
162                        tokens += Self::estimate_tokens(&t.name);
163                        tokens += Self::estimate_tokens(&t.arguments);
164                        tokens += Self::estimate_tokens(&t.id);
165                    }
166                }
167                tokens
168            }
169            ChatMessage::Tool {
170                tool_call_id,
171                content,
172                images,
173                ..
174            } => {
175                // A tool result's pictures count like any other — before this
176                // they rode the context budget for free while user pictures
177                // were overcharged.
178                let mut tokens =
179                    Self::estimate_tokens(tool_call_id) + Self::estimate_tokens(content);
180                for img in images {
181                    tokens += Self::image_tokens(img);
182                }
183                tokens
184            }
185            ChatMessage::Custom { role, data } => {
186                Self::estimate_tokens(role) + Self::estimate_tokens(&data.to_string())
187            }
188        }
189    }
190
191    /// Trim message list to keep total tokens under `max_tokens`。
192    ///
193    /// Trimming strategy:
194    /// - Always keep the first `keep_first_n` messages (typically system prompt)
195    /// - Always keep the last `keep_last_n` messages (recent conversation)
196    /// - Remove oldest messages from the middle until within budget
197    pub fn trim(&self, messages: &mut Vec<ChatMessage>) {
198        if messages.is_empty() || self.max_tokens == 0 {
199            return;
200        }
201
202        let total_tokens: usize = messages.iter().map(Self::message_tokens).sum();
203        if total_tokens <= self.max_tokens {
204            return;
205        }
206
207        let keep_first = self.keep_first_n.min(messages.len());
208        let keep_last = self
209            .keep_last_n
210            .min(messages.len().saturating_sub(keep_first));
211
212        // Trimmable range: [keep_first, messages.len() - keep_last)
213        let trim_start = keep_first;
214        let trim_end = messages.len().saturating_sub(keep_last);
215        if trim_start >= trim_end {
216            return;
217        }
218
219        let mut current_tokens: usize = total_tokens;
220        let remove_idx = trim_start;
221        let mut trim_end = trim_end;
222
223        while current_tokens > self.max_tokens && remove_idx < trim_end {
224            let removed = Self::message_tokens(&messages[remove_idx]);
225            messages.remove(remove_idx);
226            current_tokens = current_tokens.saturating_sub(removed);
227            trim_end = messages.len().saturating_sub(keep_last);
228        }
229    }
230}
231
232fn is_cjk(c: char) -> bool {
233    matches!(
234        c,
235        '\u{4E00}'..='\u{9FFF}'   // CJK Unified Ideographs
236        | '\u{3400}'..='\u{4DBF}' // CJK Unified Ideographs Extension A
237        | '\u{3000}'..='\u{303F}' // CJK Symbols and Punctuation
238        | '\u{FF00}'..='\u{FFEF}' // Halfwidth and Fullwidth Forms
239        | '\u{3040}'..='\u{309F}' // Hiragana
240        | '\u{30A0}'..='\u{30FF}' // Katakana
241        | '\u{AC00}'..='\u{D7AF}' // Hangul Syllables
242    )
243}
244
245// ── Inline Context Compaction ──────────────────────────────────────────────
246
247/// What a successful [`ContextCompaction::compact`] actually did to the
248/// history. agent-base stays strategy-free: it only relays the kind into
249/// the log line, so a nudge append never reads as a compaction and a real
250/// replacement always does (issue #33).
251#[derive(Debug, Clone, Copy, PartialEq, Eq)]
252pub enum CompactionKind {
253    /// One budget nudge appended at the end; prior messages untouched.
254    Reminder,
255    /// Last-turn nudge appended; prior messages untouched.
256    Fallback,
257    /// Messages replaced wholesale (window rotation or compression).
258    Reset,
259}
260
261impl CompactionKind {
262    /// The grep-able log line emitted when the compactor returns this kind.
263    /// The three strings are deliberately distinct: a Reminder/Fallback append
264    /// must NOT contain "compaction" (nothing was compacted — one message was
265    /// appended), while a Reset must (the history was replaced).
266    pub fn trigger_log(self) -> &'static str {
267        match self {
268            Self::Reminder => "context reminder appended",
269            Self::Fallback => "context fallback appended",
270            Self::Reset => "inline compaction triggered",
271        }
272    }
273
274    /// The completion log line, emitted after the compactor's messages are
275    /// installed. `None` for appends — they are atomic, there is nothing to
276    /// complete, and a second line would only invite misreading.
277    pub fn completion_log(self) -> Option<&'static str> {
278        match self {
279            Self::Reminder | Self::Fallback => None,
280            Self::Reset => Some("inline compaction completed (window reset)"),
281        }
282    }
283}
284
285/// Successful compaction outcome: what happened plus the messages to install.
286pub struct CompactionOutcome {
287    pub kind: CompactionKind,
288    pub messages: Vec<ChatMessage>,
289}
290
291/// Trait for inline context compaction within the react loop.
292///
293/// Implemented by agent-works's `ContextCompactor`. agent-base defines
294/// the trait to avoid circular dependencies (agent-works depends on agent-base).
295///
296/// The react loop calls [`compact`](Self::compact) after tool execution when
297/// the estimated token count exceeds a configurable threshold. This prevents
298/// context window overflow without requiring the LLM call to fail first.
299#[async_trait::async_trait]
300pub trait ContextCompaction: Send + Sync {
301    /// Compact a message history.
302    ///
303    /// Takes the current messages and returns `Some(outcome)` if an action
304    /// was performed — the outcome carries the action kind (for logging) and
305    /// the messages to install. Returns `None` if compaction was skipped
306    /// (below threshold, too few messages, or disabled).
307    ///
308    /// The react loop handles reading/writing the session — the compactor
309    /// only transforms the message list.
310    async fn compact(
311        &self,
312        session_id: &SessionId,
313        messages: &[ChatMessage],
314    ) -> Option<CompactionOutcome>;
315
316    /// Estimate current token count for the session.
317    ///
318    /// Returns `None` if the implementation cannot estimate (falls back to
319    /// `ContextWindowManager::estimate_tokens` on the react loop side).
320    fn token_count_hint(&self, session_id: &SessionId) -> Option<usize>;
321}
322
323#[cfg(test)]
324mod tests {
325    use super::*;
326    use crate::types::{ImageAttachment, ToolCallMessage};
327
328    #[test]
329    fn test_estimate_tokens_empty() {
330        assert_eq!(ContextWindowManager::estimate_tokens(""), 0);
331    }
332
333    #[test]
334    fn test_estimate_tokens_english() {
335        let text = "Hello world this is a test";
336        let tokens = ContextWindowManager::estimate_tokens(text);
337        // ~28 chars / 4 ≈ 7
338        assert!(tokens > 0 && tokens <= 15);
339    }
340
341    #[test]
342    fn test_estimate_tokens_cjk() {
343        // 4 CJK chars / 1.5 -> ceil(2.667) = 3
344        assert_eq!(ContextWindowManager::estimate_tokens("你好世界"), 3);
345    }
346
347    #[test]
348    fn test_estimate_tokens_mixed() {
349        // 2 CJK + 5 latin: 2/1.5 + 5/4 = 1.333 + 1.25 = 2.583 -> 3
350        assert_eq!(ContextWindowManager::estimate_tokens("你好hello"), 3);
351    }
352
353    #[test]
354    fn test_message_tokens_user_with_url_image() {
355        let msg = ChatMessage::user_with_images(
356            "pic",
357            vec![ImageAttachment::Url {
358                url: "http://x/a.png".into(),
359                detail: None,
360            }],
361        );
362        let base = ContextWindowManager::message_tokens(&ChatMessage::user("pic"));
363        let t = ContextWindowManager::message_tokens(&msg);
364        assert!(t > base);
365    }
366
367    #[test]
368    fn test_message_tokens_user_with_base64_image() {
369        // with media_type
370        let msg = ChatMessage::user_with_images(
371            "pic",
372            vec![ImageAttachment::Base64 {
373                data: "abcd".into(),
374                media_type: Some("image/png".into()),
375                detail: None,
376            }],
377        );
378        let base = ContextWindowManager::message_tokens(&ChatMessage::user("pic"));
379        assert!(ContextWindowManager::message_tokens(&msg) > base);
380
381        // without media_type
382        let msg = ChatMessage::user_with_images(
383            "pic",
384            vec![ImageAttachment::Base64 {
385                data: "abcd".into(),
386                media_type: None,
387                detail: None,
388            }],
389        );
390        assert!(ContextWindowManager::message_tokens(&msg) > base);
391    }
392
393    #[test]
394    fn test_message_tokens_assistant_reasoning_and_tool_calls() {
395        let msg = ChatMessage::Assistant {
396            content: Some("ans".into()),
397            reasoning_content: Some("thinking".into()),
398            tool_calls: Some(vec![ToolCallMessage {
399                id: "tc1".into(),
400                name: "echo".into(),
401                arguments: "{}".into(),
402            }]),
403            thinking_signature: None,
404        };
405        let t = ContextWindowManager::message_tokens(&msg);
406        assert!(t > 0);
407    }
408
409    #[test]
410    fn test_message_tokens_tool_and_custom() {
411        let tool = ChatMessage::tool("tc1", "done");
412        assert!(ContextWindowManager::message_tokens(&tool) > 0);
413
414        let custom = ChatMessage::Custom {
415            role: "artifact".into(),
416            data: serde_json::json!({"x": 1}),
417        };
418        assert!(ContextWindowManager::message_tokens(&custom) > 0);
419    }
420
421    /// protects: a screenshot is priced by its wire-scale PIXELS (~750 px per
422    /// token) — never by the length of its base64 payload, which billed one
423    /// 1278x1152 screenshot at ~219k tokens and fed the max_message_tokens
424    /// safety valve its victims (session 20261108_c525b6c7: two pastes
425    /// estimated at 439k, the valve popped the user message, the turn 400ed
426    /// on an empty message list). fails_when: the estimate scales with
427    /// payload bytes. no_claim: any provider's exact bill.
428    #[test]
429    fn screenshot_images_price_by_pixels_not_base64_length() {
430        let png = crate::image_ops::test_fixtures::noisy_png(1278, 1152);
431        let b64 = crate::image_ops::to_base64(&png);
432        let msg = ChatMessage::user_with_images(
433            "what is in this screenshot?",
434            vec![ImageAttachment::Base64 {
435                data: b64.clone(),
436                media_type: Some("image/png".into()),
437                detail: None,
438            }],
439        );
440        let tokens = ContextWindowManager::message_tokens(&msg);
441        // The old formula's verdict on the very same payload:
442        let old_formula = b64.len() / 4;
443        assert!(
444            old_formula > 100_000,
445            "fixture must carry the incident's payload scale, got {old_formula}"
446        );
447        assert!(
448            tokens < 5_000,
449            "one screenshot must cost thousands of tokens, not {tokens} (payload was {old_formula} under the old formula)"
450        );
451        assert!(tokens > 1_500, "the pixel price is real, got {tokens}");
452    }
453
454    /// protects: a tool result's pictures enter the estimate like any other
455    /// (they used to ride the context budget for free). fails_when: tool
456    /// images are uncounted and trim starves. no_claim: that a tool's images
457    /// and a user's images cost the same at any given provider.
458    #[test]
459    fn tool_result_images_are_counted_too() {
460        let png =
461            crate::image_ops::to_base64(&crate::image_ops::test_fixtures::noisy_png(200, 200));
462        let text_only = ChatMessage::tool("tc1", "done");
463        let with_image = ChatMessage::Tool {
464            tool_call_id: "tc1".into(),
465            name: Some("read_image".into()),
466            content: "done".into(),
467            images: vec![ImageAttachment::Base64 {
468                data: png,
469                media_type: Some("image/png".into()),
470                detail: None,
471            }],
472        };
473        let text_tokens = ContextWindowManager::message_tokens(&text_only);
474        let image_tokens = ContextWindowManager::message_tokens(&with_image);
475        assert!(
476            image_tokens > text_tokens + 100,
477            "tool image must cost its pixels: {text_tokens} vs {image_tokens}"
478        );
479    }
480
481    /// protects: a payload whose header cannot be read (exotic format, junk)
482    /// gets the capped fallback — bounded and independent of payload length,
483    /// so garbage can never inflate the estimate into the safety valve's
484    /// range. fails_when: unreadable payloads are priced by byte length or
485    /// crash the estimator. no_claim: what such a payload would really cost.
486    #[test]
487    fn unreadable_image_payloads_get_the_capped_fallback() {
488        let small: Vec<u8> = b"not an image".to_vec();
489        let mut big = vec![b'x'; 512_000];
490        big.extend_from_slice(b"also not an image");
491        let estimate = |payload: Vec<u8>| {
492            ContextWindowManager::user_message_tokens(
493                "",
494                &[ImageAttachment::Base64 {
495                    data: crate::image_ops::to_base64(&payload),
496                    media_type: None,
497                    detail: None,
498                }],
499            )
500        };
501        let small_est = estimate(small);
502        let big_est = estimate(big);
503        assert_eq!(small_est, big_est, "fallback is size-independent");
504        assert!(
505            (1_000..5_000).contains(&small_est),
506            "fallback is capped: {small_est}"
507        );
508    }
509
510    #[test]
511    fn test_trim_no_trim_needed() {
512        let mgr = ContextWindowManager::new(1000);
513        let mut msgs = vec![
514            ChatMessage::system("You are a helpful assistant."),
515            ChatMessage::user("Hello"),
516            ChatMessage::assistant("Hi there!"),
517        ];
518        let original_len = msgs.len();
519        mgr.trim(&mut msgs);
520        assert_eq!(msgs.len(), original_len);
521    }
522
523    #[test]
524    fn test_trim_keeps_first_and_last() {
525        let mgr = ContextWindowManager::new(8)
526            .with_keep_first_n(1)
527            .with_keep_last_n(2);
528        let mut msgs = vec![
529            ChatMessage::system("system"),
530            ChatMessage::user("message number one"),
531            ChatMessage::assistant("message number two"),
532            ChatMessage::user("message number three"),
533            ChatMessage::assistant("message number four"),
534            ChatMessage::user("message number five"),
535            ChatMessage::assistant("message number six"),
536        ];
537        mgr.trim(&mut msgs);
538        assert_eq!(msgs.len(), 3);
539        assert!(matches!(msgs[0], ChatMessage::System { .. }));
540    }
541}
542
543#[cfg(test)]
544mod proptest_tests {
545    use super::*;
546    use proptest::prelude::*;
547
548    proptest! {
549        #[test]
550        fn estimate_tokens_never_panics(text in ".*") {
551            let tokens = ContextWindowManager::estimate_tokens(&text);
552            // tokens should be non-negative (usize) and reasonable
553            assert!(tokens <= text.len() + 1); // at most 1 token per byte + ceil
554        }
555
556        #[test]
557        fn estimate_tokens_empty_is_zero(text in "[a-z\u{4e00}-\u{9fff}]{0,100}") {
558            if text.is_empty() {
559                assert_eq!(ContextWindowManager::estimate_tokens(&text), 0);
560            } else {
561                assert!(ContextWindowManager::estimate_tokens(&text) > 0);
562            }
563        }
564
565        #[test]
566        fn estimate_tokens_cjk_higher_than_latin_same_len(
567            cjk_text in "[\u{4e00}-\u{9fff}]{1,50}",
568            latin_text in "[a-z]{1,50}",
569        ) {
570            // Pad to same char length
571            let max_len = cjk_text.chars().count().max(latin_text.chars().count());
572            let cjk_padded: String = cjk_text.chars().cycle().take(max_len).collect();
573            let latin_padded: String = latin_text.chars().cycle().take(max_len).collect();
574            let cjk_tokens = ContextWindowManager::estimate_tokens(&cjk_padded);
575            let latin_tokens = ContextWindowManager::estimate_tokens(&latin_padded);
576            // CJK ~1.5 chars/token, Latin ~4 chars/token → CJK uses more tokens
577            assert!(cjk_tokens >= latin_tokens,
578                "CJK ({}) should use >= tokens than Latin ({}) for {} chars",
579                cjk_tokens, latin_tokens, max_len);
580        }
581
582        #[test]
583        fn trim_preserves_system_prefix(
584            num_messages in 2usize..15,
585            max_tokens in 5usize..50,
586        ) {
587            let mgr = ContextWindowManager {
588                max_tokens,
589                keep_first_n: 1,
590                keep_last_n: 0,
591            };
592            let mut msgs = vec![ChatMessage::system("system prompt")];
593            for i in 0..num_messages {
594                msgs.push(ChatMessage::user(format!("message {}", i)));
595            }
596            mgr.trim(&mut msgs);
597            // System message should always be preserved
598            assert!(!msgs.is_empty());
599            assert!(matches!(msgs[0], ChatMessage::System { .. }));
600        }
601
602        #[test]
603        fn trim_result_within_budget(
604            num_messages in 3usize..15,
605            max_tokens in 10usize..100,
606        ) {
607            let mgr = ContextWindowManager {
608                max_tokens,
609                keep_first_n: 1,
610                keep_last_n: 1,
611            };
612            let mut msgs = vec![ChatMessage::system("sys")];
613            for i in 0..num_messages {
614                msgs.push(ChatMessage::user(format!("msg {}", i)));
615            }
616            let total_before: usize = msgs.iter().map(ContextWindowManager::message_tokens).sum();
617            // Only test when we actually exceed budget
618            if total_before > max_tokens {
619                mgr.trim(&mut msgs);
620                let total_after: usize = msgs.iter().map(ContextWindowManager::message_tokens).sum();
621                // After trimming, should be within budget (or couldn't trim more)
622                assert!(total_after <= total_before);
623            }
624        }
625    }
626
627    // ── CompactionKind log dispatch (issue #33) ──
628
629    #[test]
630    fn compaction_kind_log_lines_are_grep_able() {
631        use super::{CompactionKind, CompactionOutcome};
632
633        // A nudge append must never read as a compaction in the log...
634        for kind in [CompactionKind::Reminder, CompactionKind::Fallback] {
635            let trigger = kind.trigger_log();
636            assert!(
637                !trigger.contains("compaction"),
638                "{kind:?} trigger log must not claim compaction: {trigger}"
639            );
640            assert!(
641                kind.completion_log().is_none(),
642                "{kind:?} append is atomic — no completion line"
643            );
644        }
645        // ...while a real replacement must say compaction.
646        let reset = CompactionKind::Reset;
647        assert!(reset.trigger_log().contains("compaction"));
648        let completion = reset.completion_log().expect("reset has a completion line");
649        assert!(completion.contains("compaction"));
650
651        // The three kinds are distinguishable by grep in session.log.
652        let all = [
653            CompactionKind::Reminder.trigger_log(),
654            CompactionKind::Fallback.trigger_log(),
655            reset.trigger_log(),
656        ];
657        for (i, a) in all.iter().enumerate() {
658            for b in all.iter().skip(i + 1) {
659                assert_ne!(a, b, "trigger log lines must be distinct");
660            }
661        }
662
663        // Outcome struct: kind + messages travel together.
664        let outcome = CompactionOutcome {
665            kind: CompactionKind::Reminder,
666            messages: vec![ChatMessage::user("nudge")],
667        };
668        assert_eq!(outcome.kind, CompactionKind::Reminder);
669        assert_eq!(outcome.messages.len(), 1);
670    }
671}