Skip to main content

gemini_adk_fluent_rs/compose/
context.rs

1//! C — Context engineering.
2//!
3//! Chain context rewrites with `>>`: each rewrites the history the previous
4//! one produced, so order matters (`C::prepend(..) >> C::window(10)`).
5
6use std::sync::Arc;
7
8use async_trait::async_trait;
9use gemini_adk_rs::error::AgentError;
10use gemini_adk_rs::llm::LlmRequest;
11use gemini_adk_rs::middleware::Middleware;
12use gemini_genai_rs::prelude::Content;
13
14/// Rewrites a conversation history into a new one.
15type HistoryFilter = Arc<dyn Fn(&[Content]) -> Vec<Content> + Send + Sync>;
16
17/// A context policy that filters/transforms conversation history.
18#[derive(Clone)]
19pub struct ContextPolicy {
20    name: &'static str,
21    filter: HistoryFilter,
22}
23
24impl ContextPolicy {
25    fn new(
26        name: &'static str,
27        f: impl Fn(&[Content]) -> Vec<Content> + Send + Sync + 'static,
28    ) -> Self {
29        Self {
30            name,
31            filter: Arc::new(f),
32        }
33    }
34
35    /// Apply this policy to conversation history.
36    pub fn apply(&self, history: &[Content]) -> Vec<Content> {
37        (self.filter)(history)
38    }
39
40    /// Name of this policy.
41    pub fn name(&self) -> &str {
42        self.name
43    }
44}
45
46impl std::fmt::Debug for ContextPolicy {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        f.debug_struct("ContextPolicy")
49            .field("name", &self.name)
50            .finish()
51    }
52}
53
54/// Chain two context rewrites with `>>`: `self` first, then `rhs`.
55/// The combined policy applies both filters and merges (deduplicates) results.
56impl std::ops::Shr for ContextPolicy {
57    type Output = ContextComposite;
58
59    fn shr(self, rhs: ContextPolicy) -> Self::Output {
60        ContextComposite {
61            policies: vec![self, rhs],
62        }
63    }
64}
65
66/// A chain of context policies applied in combination (`C::a() >> C::b()`).
67#[derive(Clone)]
68#[non_exhaustive]
69pub struct ContextComposite {
70    /// The ordered list of policies in this chain.
71    pub policies: Vec<ContextPolicy>,
72}
73
74impl ContextComposite {
75    /// Apply all policies in sequence, piping each policy's output into the
76    /// next. For `C::window(10) >> C::user_only()` this means "take the last 10
77    /// turns, then keep only the user turns" — the additive `+` composes the
78    /// transforms rather than unioning their independent results.
79    pub fn apply(&self, history: &[Content]) -> Vec<Content> {
80        let mut current = history.to_vec();
81        for policy in &self.policies {
82            current = policy.apply(&current);
83        }
84        current
85    }
86
87    /// Adapt this policy chain into a `transform_request` middleware layer that
88    /// rewrites the request's conversation history before it reaches the model.
89    pub fn into_middleware(self) -> Arc<dyn Middleware> {
90        Arc::new(ContextMiddleware { chain: self })
91    }
92}
93
94/// A single policy is a one-element chain, so `.context(C::window(10))` works
95/// without an explicit `+`.
96impl From<ContextPolicy> for ContextComposite {
97    fn from(policy: ContextPolicy) -> Self {
98        ContextComposite {
99            policies: vec![policy],
100        }
101    }
102}
103
104/// Middleware adapter that applies a [`ContextComposite`] to the request
105/// history on every model call.
106struct ContextMiddleware {
107    chain: ContextComposite,
108}
109
110#[async_trait]
111impl Middleware for ContextMiddleware {
112    fn name(&self) -> &str {
113        "context"
114    }
115
116    async fn transform_request(&self, request: &mut LlmRequest) -> Result<(), AgentError> {
117        request.contents = self.chain.apply(&request.contents);
118        Ok(())
119    }
120}
121
122impl std::ops::Shr<ContextPolicy> for ContextComposite {
123    type Output = ContextComposite;
124
125    fn shr(mut self, rhs: ContextPolicy) -> Self::Output {
126        self.policies.push(rhs);
127        self
128    }
129}
130
131/// The `C` namespace — static factory methods for context policies.
132pub struct C;
133
134impl C {
135    /// Keep only the last `n` messages.
136    pub fn window(n: usize) -> ContextPolicy {
137        ContextPolicy::new("window", move |history| {
138            if history.len() > n {
139                history[history.len() - n..].to_vec()
140            } else {
141                history.to_vec()
142            }
143        })
144    }
145
146    /// Keep only messages with role "user".
147    pub fn user_only() -> ContextPolicy {
148        use gemini_genai_rs::prelude::Role;
149        ContextPolicy::new("user_only", move |history| {
150            history
151                .iter()
152                .filter(|c| c.role == Some(Role::User))
153                .cloned()
154                .collect()
155        })
156    }
157
158    /// Apply a custom filter function.
159    pub fn custom(f: impl Fn(&[Content]) -> Vec<Content> + Send + Sync + 'static) -> ContextPolicy {
160        ContextPolicy::new("custom", f)
161    }
162
163    /// Keep only messages with role "model".
164    pub fn model_only() -> ContextPolicy {
165        use gemini_genai_rs::prelude::Role;
166        ContextPolicy::new("model_only", move |history| {
167            history
168                .iter()
169                .filter(|c| c.role == Some(Role::Model))
170                .cloned()
171                .collect()
172        })
173    }
174
175    /// Keep the first `n` messages (head).
176    pub fn head(n: usize) -> ContextPolicy {
177        ContextPolicy::new("head", move |history| {
178            history.iter().take(n).cloned().collect()
179        })
180    }
181
182    /// Keep every `n`-th message (sampling).
183    pub fn sample(n: usize) -> ContextPolicy {
184        ContextPolicy::new("sample", move |history| {
185            history
186                .iter()
187                .enumerate()
188                .filter(|(i, _)| i % n == 0)
189                .map(|(_, c)| c.clone())
190                .collect()
191        })
192    }
193
194    /// Exclude messages that contain tool-related parts (function calls/responses).
195    pub fn exclude_tools() -> ContextPolicy {
196        use gemini_genai_rs::prelude::Part;
197        ContextPolicy::new("exclude_tools", move |history| {
198            history
199                .iter()
200                .filter(|c| {
201                    c.parts.iter().all(|p| {
202                        !matches!(p, Part::FunctionCall { .. } | Part::FunctionResponse { .. })
203                    })
204                })
205                .cloned()
206                .collect()
207        })
208    }
209
210    /// Prepend a system message to the context.
211    pub fn prepend(content: Content) -> ContextPolicy {
212        ContextPolicy::new("prepend", move |history| {
213            let mut result = vec![content.clone()];
214            result.extend(history.iter().cloned());
215            result
216        })
217    }
218
219    /// Append a content to the context.
220    pub fn append(content: Content) -> ContextPolicy {
221        ContextPolicy::new("append", move |history| {
222            let mut result = history.to_vec();
223            result.push(content.clone());
224            result
225        })
226    }
227
228    /// Keep only messages that contain text parts.
229    pub fn text_only() -> ContextPolicy {
230        use gemini_genai_rs::prelude::Part;
231        ContextPolicy::new("text_only", move |history| {
232            history
233                .iter()
234                .filter(|c| c.parts.iter().any(|p| matches!(p, Part::Text { .. })))
235                .cloned()
236                .collect()
237        })
238    }
239
240    /// Filter messages by a predicate on Content.
241    pub fn filter(f: impl Fn(&Content) -> bool + Send + Sync + 'static) -> ContextPolicy {
242        ContextPolicy::new("filter", move |history| {
243            history.iter().filter(|c| f(c)).cloned().collect()
244        })
245    }
246
247    /// Map/transform each message in the context.
248    pub fn map(f: impl Fn(&Content) -> Content + Send + Sync + 'static) -> ContextPolicy {
249        ContextPolicy::new("map", move |history| history.iter().map(&f).collect())
250    }
251
252    /// Truncate context to approximately `max_chars` total characters of text.
253    pub fn truncate(max_chars: usize) -> ContextPolicy {
254        use gemini_genai_rs::prelude::Part;
255        ContextPolicy::new("truncate", move |history| {
256            let mut total = 0;
257            let mut result = Vec::new();
258            // Work backwards to keep most recent messages
259            for c in history.iter().rev() {
260                let text_len: usize = c
261                    .parts
262                    .iter()
263                    .filter_map(|p| match p {
264                        Part::Text { text } => Some(text.len()),
265                        _ => None,
266                    })
267                    .sum();
268                if total + text_len > max_chars && !result.is_empty() {
269                    break;
270                }
271                total += text_len;
272                result.push(c.clone());
273            }
274            result.reverse();
275            result
276        })
277    }
278
279    /// Return an empty context (useful for isolated agents).
280    pub fn empty() -> ContextPolicy {
281        ContextPolicy::new("empty", |_| Vec::new())
282    }
283
284    /// Inject state values as context preamble.
285    ///
286    /// Bridges Channel 2 (State) → Channel 1 (Conversation History) by prepending
287    /// formatted state values as a system context message.
288    ///
289    /// # Example
290    /// ```
291    /// # use gemini_adk_fluent_rs::prelude::*;
292    /// let policy = C::from_state(&["user:name", "app:account_balance", "derived:risk"]);
293    /// // Produces: "[Context: name=John, account_balance=$5230, risk=0.72]"
294    /// # let _ = policy;
295    /// ```
296    pub fn from_state(keys: &[&str]) -> ContextPolicy {
297        let owned_keys: Vec<String> = keys.iter().map(std::string::ToString::to_string).collect();
298        ContextPolicy::new("from_state", move |history| {
299            // Note: This policy captures keys but cannot access State at filter time.
300            // The actual state injection happens at the Live session level via
301            // instruction_template or on_turn_boundary. This policy prepends a
302            // placeholder that the runtime populates.
303            let mut result = Vec::new();
304            if !owned_keys.is_empty() {
305                let key_list = owned_keys.join(", ");
306                result.push(Content::user(format!("[Context keys: {key_list}]")));
307            }
308            result.extend(history.iter().cloned());
309            result
310        })
311    }
312
313    /// Template-based context injection with `{key}` placeholders.
314    ///
315    /// Replaces placeholders in the template with state key references.
316    pub fn template(tpl: &str) -> ContextPolicy {
317        let tpl = tpl.to_string();
318        ContextPolicy::new("template", move |history| {
319            let mut result = vec![Content::user(tpl.clone())];
320            result.extend(history.iter().cloned());
321            result
322        })
323    }
324
325    /// Conditional context — applies inner policy only when predicate is true.
326    ///
327    /// Falls back to passing history through unchanged.
328    pub fn when(
329        predicate: impl Fn() -> bool + Send + Sync + 'static,
330        inner: ContextPolicy,
331    ) -> ContextPolicy {
332        ContextPolicy::new("when", move |history| {
333            if predicate() {
334                inner.apply(history)
335            } else {
336                history.to_vec()
337            }
338        })
339    }
340
341    /// Redact patterns from context messages.
342    pub fn redact(patterns: &[&str]) -> ContextPolicy {
343        use gemini_genai_rs::prelude::Part;
344        let patterns: Vec<String> = patterns
345            .iter()
346            .map(std::string::ToString::to_string)
347            .collect();
348        ContextPolicy::new("redact", move |history| {
349            history
350                .iter()
351                .map(|c| {
352                    let parts: Vec<Part> = c
353                        .parts
354                        .iter()
355                        .map(|p| match p {
356                            Part::Text { text } => {
357                                let mut redacted = text.clone();
358                                for pattern in &patterns {
359                                    redacted = redacted.replace(pattern.as_str(), "[REDACTED]");
360                                }
361                                Part::Text { text: redacted }
362                            }
363                            other => other.clone(),
364                        })
365                        .collect();
366                    Content {
367                        role: c.role,
368                        parts,
369                    }
370                })
371                .collect()
372        })
373    }
374
375    /// LLM-powered context summarization.
376    ///
377    /// Stores a summarization prompt that the runtime uses to condense context
378    /// via an LLM call before passing it to the agent. The policy prepends a
379    /// marker so the runtime knows summarization is requested.
380    ///
381    /// # Example
382    /// ```
383    /// # use gemini_adk_fluent_rs::prelude::*;
384    /// let policy = C::summarize("Summarize the conversation focusing on action items");
385    /// # let _ = policy;
386    /// ```
387    pub fn summarize(prompt: &str) -> ContextPolicy {
388        let prompt = prompt.to_string();
389        ContextPolicy::new("summarize", move |history| {
390            let mut result = vec![Content::user(format!("[Summarize context: {prompt}]"))];
391            result.extend(history.iter().cloned());
392            result
393        })
394    }
395
396    /// Keep only context relevant to a state key.
397    ///
398    /// Marker policy for LLM-powered relevance filtering. The runtime uses
399    /// the referenced state key's value to filter context entries by relevance.
400    ///
401    /// # Example
402    /// ```
403    /// # use gemini_adk_fluent_rs::prelude::*;
404    /// let policy = C::relevant("user:current_topic");
405    /// # let _ = policy;
406    /// ```
407    pub fn relevant(query_key: &str) -> ContextPolicy {
408        let key = query_key.to_string();
409        ContextPolicy::new("relevant", move |history| {
410            let mut result = vec![Content::user(format!(
411                "[Filter context relevant to state key: {key}]"
412            ))];
413            result.extend(history.iter().cloned());
414            result
415        })
416    }
417
418    /// Extract specific information from context.
419    ///
420    /// Marker policy that signals the runtime to extract only the named
421    /// pieces of information from the conversation history via an LLM call.
422    ///
423    /// # Example
424    /// ```
425    /// # use gemini_adk_fluent_rs::prelude::*;
426    /// let policy = C::extract(&["customer_name", "order_id", "complaint"]);
427    /// # let _ = policy;
428    /// ```
429    pub fn extract(keys: &[&str]) -> ContextPolicy {
430        let owned_keys: Vec<String> = keys.iter().map(std::string::ToString::to_string).collect();
431        ContextPolicy::new("extract", move |history| {
432            let mut result = vec![Content::user(format!(
433                "[Extract from context: {}]",
434                owned_keys.join(", ")
435            ))];
436            result.extend(history.iter().cloned());
437            result
438        })
439    }
440
441    /// Distill context to essential information.
442    ///
443    /// Marker policy for LLM-powered distillation. Similar to `summarize` but
444    /// focused on extracting only the essential facts per the given instruction.
445    ///
446    /// # Example
447    /// ```
448    /// # use gemini_adk_fluent_rs::prelude::*;
449    /// let policy = C::distill("Keep only decisions made and their rationale");
450    /// # let _ = policy;
451    /// ```
452    pub fn distill(instruction: &str) -> ContextPolicy {
453        let instruction = instruction.to_string();
454        ContextPolicy::new("distill", move |history| {
455            let mut result = vec![Content::user(format!("[Distill context: {instruction}]"))];
456            result.extend(history.iter().cloned());
457            result
458        })
459    }
460
461    /// Priority-weighted context selection.
462    ///
463    /// Assigns weights to context entries by role or content pattern. Higher
464    /// weight entries are kept preferentially when context must be truncated.
465    /// Weights are encoded as a marker for runtime processing.
466    ///
467    /// # Example
468    /// ```
469    /// # use gemini_adk_fluent_rs::prelude::*;
470    /// let policy = C::priority(&[("user", 1.0), ("model", 0.5), ("tool", 0.2)]);
471    /// # let _ = policy;
472    /// ```
473    pub fn priority(weights: &[(&str, f64)]) -> ContextPolicy {
474        let owned_weights: Vec<(String, f64)> =
475            weights.iter().map(|(k, v)| (k.to_string(), *v)).collect();
476        ContextPolicy::new("priority", move |history| {
477            let weight_str = owned_weights
478                .iter()
479                .map(|(k, v)| format!("{k}={v}"))
480                .collect::<Vec<_>>()
481                .join(", ");
482            let mut result = vec![Content::user(format!("[Priority weights: {weight_str}]"))];
483            result.extend(history.iter().cloned());
484            result
485        })
486    }
487
488    /// Fit context to a token budget with smart truncation.
489    ///
490    /// Similar to [`truncate`](Self::truncate) (a character budget, ~4 chars per token) but adds a truncation marker so the
491    /// runtime knows content was trimmed, allowing the agent to request more
492    /// context if needed.
493    ///
494    /// # Example
495    /// ```
496    /// # use gemini_adk_fluent_rs::prelude::*;
497    /// let policy = C::fit(4096);
498    /// # let _ = policy;
499    /// ```
500    pub fn fit(max_tokens: usize) -> ContextPolicy {
501        use gemini_genai_rs::prelude::Part;
502        let max_chars = max_tokens * 4; // rough estimate: 4 chars per token
503        ContextPolicy::new("fit", move |history| {
504            let mut total = 0;
505            let mut result = Vec::new();
506            // Work backwards to keep most recent messages
507            for c in history.iter().rev() {
508                let text_len: usize = c
509                    .parts
510                    .iter()
511                    .filter_map(|p| match p {
512                        Part::Text { text } => Some(text.len()),
513                        _ => None,
514                    })
515                    .sum();
516                if total + text_len > max_chars && !result.is_empty() {
517                    // Prepend truncation marker
518                    result.push(Content::user(format!(
519                        "[Context truncated to fit ~{} token budget; {} earlier messages omitted]",
520                        max_tokens,
521                        history.len() - result.len()
522                    )));
523                    break;
524                }
525                total += text_len;
526                result.push(c.clone());
527            }
528            result.reverse();
529            result
530        })
531    }
532
533    /// Project/keep only specific fields from context.
534    ///
535    /// Marker policy that signals the runtime to retain only the named fields
536    /// from structured content in the conversation history.
537    ///
538    /// # Example
539    /// ```
540    /// # use gemini_adk_fluent_rs::prelude::*;
541    /// let policy = C::project(&["name", "status", "priority"]);
542    /// # let _ = policy;
543    /// ```
544    pub fn project(fields: &[&str]) -> ContextPolicy {
545        let owned_fields: Vec<String> = fields
546            .iter()
547            .map(std::string::ToString::to_string)
548            .collect();
549        ContextPolicy::new("project", move |history| {
550            let mut result = vec![Content::user(format!(
551                "[Project fields: {}]",
552                owned_fields.join(", ")
553            ))];
554            result.extend(history.iter().cloned());
555            result
556        })
557    }
558
559    /// Select context entries matching a predicate.
560    ///
561    /// Similar to [`filter`](Self::filter) but with select semantics: entries
562    /// matching the predicate are included (positive selection).
563    pub fn select(predicate: impl Fn(&Content) -> bool + Send + Sync + 'static) -> ContextPolicy {
564        ContextPolicy::new("select", move |history| {
565            history.iter().filter(|c| predicate(c)).cloned().collect()
566        })
567    }
568
569    /// Include context only from specific agents.
570    ///
571    /// Filters context to keep only messages attributed to the named agents.
572    /// Agent attribution is detected via `[Agent: name]` markers in content.
573    ///
574    /// # Example
575    /// ```
576    /// # use gemini_adk_fluent_rs::prelude::*;
577    /// let policy = C::from_agents(&["researcher", "analyst"]);
578    /// # let _ = policy;
579    /// ```
580    pub fn from_agents(names: &[&str]) -> ContextPolicy {
581        let owned_names: Vec<String> = names.iter().map(std::string::ToString::to_string).collect();
582        ContextPolicy::new("from_agents", move |history| {
583            history
584                .iter()
585                .filter(|c| {
586                    c.parts.iter().any(|p| match p {
587                        gemini_genai_rs::prelude::Part::Text { text } => owned_names
588                            .iter()
589                            .any(|name| text.contains(&format!("[Agent: {name}]"))),
590                        _ => false,
591                    })
592                })
593                .cloned()
594                .collect()
595        })
596    }
597
598    /// Exclude context from specific agents.
599    ///
600    /// Filters out messages attributed to the named agents. Agent attribution
601    /// is detected via `[Agent: name]` markers in content.
602    ///
603    /// # Example
604    /// ```
605    /// # use gemini_adk_fluent_rs::prelude::*;
606    /// let policy = C::exclude_agents(&["logger", "debugger"]);
607    /// # let _ = policy;
608    /// ```
609    pub fn exclude_agents(names: &[&str]) -> ContextPolicy {
610        let owned_names: Vec<String> = names.iter().map(std::string::ToString::to_string).collect();
611        ContextPolicy::new("exclude_agents", move |history| {
612            history
613                .iter()
614                .filter(|c| {
615                    !c.parts.iter().any(|p| match p {
616                        gemini_genai_rs::prelude::Part::Text { text } => owned_names
617                            .iter()
618                            .any(|name| text.contains(&format!("[Agent: {name}]"))),
619                        _ => false,
620                    })
621                })
622                .cloned()
623                .collect()
624        })
625    }
626
627    /// Scratchpad: read notes from a state key as context.
628    ///
629    /// Prepends the value of a state key as a notes/scratchpad section in the
630    /// context. Useful for maintaining running notes across turns.
631    ///
632    /// # Example
633    /// ```
634    /// # use gemini_adk_fluent_rs::prelude::*;
635    /// let policy = C::notes("session:scratchpad");
636    /// # let _ = policy;
637    /// ```
638    pub fn notes(key: &str) -> ContextPolicy {
639        let key = key.to_string();
640        ContextPolicy::new("notes", move |history| {
641            let mut result = vec![Content::user(format!("[Scratchpad from state key: {key}]"))];
642            result.extend(history.iter().cloned());
643            result
644        })
645    }
646
647    /// Pipeline-aware context that adapts based on pipeline position.
648    ///
649    /// Marker policy that signals the runtime to adjust context based on
650    /// where the current agent sits in a pipeline. Early stages receive full
651    /// context; later stages receive only the outputs of preceding stages.
652    ///
653    /// # Example
654    /// ```
655    /// # use gemini_adk_fluent_rs::prelude::*;
656    /// let policy = C::pipeline_aware();
657    /// # let _ = policy;
658    /// ```
659    pub fn pipeline_aware() -> ContextPolicy {
660        ContextPolicy::new("pipeline_aware", |history| {
661            let mut result = vec![Content::user(
662                "[Pipeline-aware: adapt context to pipeline position]".to_string(),
663            )];
664            result.extend(history.iter().cloned());
665            result
666        })
667    }
668
669    /// Deduplicate adjacent messages with identical text content.
670    pub fn dedup() -> ContextPolicy {
671        use gemini_genai_rs::prelude::Part;
672        ContextPolicy::new("dedup", |history| {
673            fn extract_text(c: &Content) -> String {
674                c.parts
675                    .iter()
676                    .filter_map(|p| match p {
677                        Part::Text { text } => Some(text.as_str()),
678                        _ => None,
679                    })
680                    .collect()
681            }
682            let mut result: Vec<Content> = Vec::new();
683            for c in history {
684                let dominated = result.last().is_some_and(|prev| {
685                    let prev_text = extract_text(prev);
686                    let curr_text = extract_text(c);
687                    prev_text == curr_text && !prev_text.is_empty()
688                });
689                if !dominated {
690                    result.push(c.clone());
691                }
692            }
693            result
694        })
695    }
696}
697
698#[cfg(test)]
699mod tests {
700    use super::*;
701    use gemini_genai_rs::prelude::Content;
702
703    #[test]
704    fn window_limits_messages() {
705        let history = vec![Content::user("a"), Content::model("b"), Content::user("c")];
706        let result = C::window(2).apply(&history);
707        assert_eq!(result.len(), 2);
708    }
709
710    #[test]
711    fn window_keeps_all_if_under_limit() {
712        let history = vec![Content::user("a")];
713        let result = C::window(5).apply(&history);
714        assert_eq!(result.len(), 1);
715    }
716
717    #[test]
718    fn user_only_filters() {
719        let history = vec![Content::user("a"), Content::model("b"), Content::user("c")];
720        let result = C::user_only().apply(&history);
721        assert_eq!(result.len(), 2);
722    }
723
724    #[test]
725    fn compose_with_add() {
726        let chain = C::window(10) >> C::user_only();
727        assert_eq!(chain.policies.len(), 2);
728    }
729
730    #[test]
731    fn chain_extends_with_add() {
732        let chain = C::window(10) >> C::user_only() >> C::custom(<[Content]>::to_vec);
733        assert_eq!(chain.policies.len(), 3);
734    }
735
736    #[test]
737    fn model_only_filters() {
738        let history = vec![Content::user("a"), Content::model("b"), Content::user("c")];
739        let result = C::model_only().apply(&history);
740        assert_eq!(result.len(), 1);
741    }
742
743    #[test]
744    fn head_keeps_first_n() {
745        let history = vec![Content::user("a"), Content::model("b"), Content::user("c")];
746        let result = C::head(2).apply(&history);
747        assert_eq!(result.len(), 2);
748    }
749
750    #[test]
751    fn sample_every_nth() {
752        let history = vec![
753            Content::user("a"),
754            Content::model("b"),
755            Content::user("c"),
756            Content::model("d"),
757        ];
758        let result = C::sample(2).apply(&history);
759        assert_eq!(result.len(), 2);
760    }
761
762    #[test]
763    fn empty_returns_nothing() {
764        let history = vec![Content::user("a"), Content::model("b")];
765        let result = C::empty().apply(&history);
766        assert!(result.is_empty());
767    }
768
769    #[test]
770    fn last_is_alias_for_window() {
771        let history = vec![Content::user("a"), Content::model("b"), Content::user("c")];
772        let result = C::window(1).apply(&history);
773        assert_eq!(result.len(), 1);
774    }
775
776    #[test]
777    fn text_only_filters_non_text() {
778        let history = vec![Content::user("text msg")];
779        let result = C::text_only().apply(&history);
780        assert_eq!(result.len(), 1);
781    }
782
783    #[test]
784    fn filter_with_predicate() {
785        use gemini_genai_rs::prelude::Part;
786        let history = vec![
787            Content::user("keep"),
788            Content::user("skip"),
789            Content::user("keep this too"),
790        ];
791        let result = C::filter(|c| {
792            c.parts.iter().any(|p| match p {
793                Part::Text { text } => text.contains("keep"),
794                _ => false,
795            })
796        })
797        .apply(&history);
798        assert_eq!(result.len(), 2);
799    }
800
801    #[test]
802    fn dedup_removes_adjacent_duplicates() {
803        let history = vec![
804            Content::user("hello"),
805            Content::user("hello"),
806            Content::user("world"),
807            Content::user("world"),
808            Content::user("world"),
809        ];
810        let result = C::dedup().apply(&history);
811        assert_eq!(result.len(), 2);
812    }
813
814    #[test]
815    fn prepend_adds_to_front() {
816        let history = vec![Content::user("existing")];
817        let result = C::prepend(Content::model("system")).apply(&history);
818        assert_eq!(result.len(), 2);
819    }
820
821    #[test]
822    fn append_adds_to_back() {
823        let history = vec![Content::user("existing")];
824        let result = C::append(Content::model("suffix")).apply(&history);
825        assert_eq!(result.len(), 2);
826    }
827
828    #[test]
829    fn from_state_prepends_context() {
830        let history = vec![Content::user("hello")];
831        let result = C::from_state(&["user:name", "app:balance"]).apply(&history);
832        assert_eq!(result.len(), 2);
833        // First message should be the context keys
834        if let gemini_genai_rs::prelude::Part::Text { text } = &result[0].parts[0] {
835            assert!(text.contains("user:name"));
836            assert!(text.contains("app:balance"));
837        } else {
838            panic!("Expected text part");
839        }
840    }
841
842    #[test]
843    fn summarize_prepends_marker() {
844        let history = vec![Content::user("hello"), Content::model("hi")];
845        let result = C::summarize("Focus on action items").apply(&history);
846        assert_eq!(result.len(), 3);
847        if let gemini_genai_rs::prelude::Part::Text { text } = &result[0].parts[0] {
848            assert!(text.contains("Summarize context"));
849            assert!(text.contains("action items"));
850        } else {
851            panic!("Expected text part");
852        }
853    }
854
855    #[test]
856    fn relevant_prepends_key_marker() {
857        let history = vec![Content::user("hello")];
858        let result = C::relevant("user:topic").apply(&history);
859        assert_eq!(result.len(), 2);
860        if let gemini_genai_rs::prelude::Part::Text { text } = &result[0].parts[0] {
861            assert!(text.contains("user:topic"));
862        } else {
863            panic!("Expected text part");
864        }
865    }
866
867    #[test]
868    fn extract_prepends_keys_marker() {
869        let history = vec![Content::user("hello")];
870        let result = C::extract(&["name", "order_id"]).apply(&history);
871        assert_eq!(result.len(), 2);
872        if let gemini_genai_rs::prelude::Part::Text { text } = &result[0].parts[0] {
873            assert!(text.contains("name"));
874            assert!(text.contains("order_id"));
875        } else {
876            panic!("Expected text part");
877        }
878    }
879
880    #[test]
881    fn distill_prepends_instruction_marker() {
882        let history = vec![Content::user("hello")];
883        let result = C::distill("Keep only decisions").apply(&history);
884        assert_eq!(result.len(), 2);
885        if let gemini_genai_rs::prelude::Part::Text { text } = &result[0].parts[0] {
886            assert!(text.contains("Distill context"));
887            assert!(text.contains("decisions"));
888        } else {
889            panic!("Expected text part");
890        }
891    }
892
893    #[test]
894    fn priority_prepends_weights_marker() {
895        let history = vec![Content::user("hello")];
896        let result = C::priority(&[("user", 1.0), ("model", 0.5)]).apply(&history);
897        assert_eq!(result.len(), 2);
898        if let gemini_genai_rs::prelude::Part::Text { text } = &result[0].parts[0] {
899            assert!(text.contains("Priority weights"));
900            assert!(text.contains("user=1"));
901            assert!(text.contains("model=0.5"));
902        } else {
903            panic!("Expected text part");
904        }
905    }
906
907    #[test]
908    fn fit_truncates_with_marker() {
909        // Create history that exceeds budget
910        let long_msg = "a".repeat(500);
911        let history = vec![
912            Content::user(long_msg.clone()),
913            Content::user(long_msg.clone()),
914            Content::user("recent"),
915        ];
916        // Budget of 10 tokens ~ 40 chars, only "recent" fits
917        let result = C::fit(10).apply(&history);
918        // Should have the recent message + truncation marker
919        assert!(result.len() <= 3);
920        // Check that truncation marker exists somewhere
921        let has_marker = result.iter().any(|c| {
922            c.parts.iter().any(|p| match p {
923                gemini_genai_rs::prelude::Part::Text { text } => text.contains("truncated"),
924                _ => false,
925            })
926        });
927        assert!(has_marker);
928    }
929
930    #[test]
931    fn fit_keeps_all_when_under_budget() {
932        let history = vec![Content::user("hi"), Content::model("hello")];
933        let result = C::fit(1000).apply(&history);
934        assert_eq!(result.len(), 2);
935    }
936
937    #[test]
938    fn project_prepends_fields_marker() {
939        let history = vec![Content::user("hello")];
940        let result = C::project(&["name", "status"]).apply(&history);
941        assert_eq!(result.len(), 2);
942        if let gemini_genai_rs::prelude::Part::Text { text } = &result[0].parts[0] {
943            assert!(text.contains("Project fields"));
944            assert!(text.contains("name"));
945            assert!(text.contains("status"));
946        } else {
947            panic!("Expected text part");
948        }
949    }
950
951    #[test]
952    fn select_filters_matching() {
953        use gemini_genai_rs::prelude::Role;
954        let history = vec![
955            Content::user("keep"),
956            Content::model("skip"),
957            Content::user("also keep"),
958        ];
959        let result = C::select(|c| c.role == Some(Role::User)).apply(&history);
960        assert_eq!(result.len(), 2);
961    }
962
963    #[test]
964    fn from_agents_filters_by_agent_marker() {
965        let history = vec![
966            Content::user("[Agent: researcher] Found data"),
967            Content::user("[Agent: logger] Debug info"),
968            Content::user("[Agent: researcher] More data"),
969        ];
970        let result = C::from_agents(&["researcher"]).apply(&history);
971        assert_eq!(result.len(), 2);
972    }
973
974    #[test]
975    fn exclude_agents_removes_agent_messages() {
976        let history = vec![
977            Content::user("[Agent: researcher] Found data"),
978            Content::user("[Agent: logger] Debug info"),
979            Content::user("[Agent: researcher] More data"),
980        ];
981        let result = C::exclude_agents(&["logger"]).apply(&history);
982        assert_eq!(result.len(), 2);
983    }
984
985    #[test]
986    fn notes_prepends_scratchpad_marker() {
987        let history = vec![Content::user("hello")];
988        let result = C::notes("session:scratchpad").apply(&history);
989        assert_eq!(result.len(), 2);
990        if let gemini_genai_rs::prelude::Part::Text { text } = &result[0].parts[0] {
991            assert!(text.contains("Scratchpad"));
992            assert!(text.contains("session:scratchpad"));
993        } else {
994            panic!("Expected text part");
995        }
996    }
997
998    #[test]
999    fn pipeline_aware_prepends_marker() {
1000        let history = vec![Content::user("hello")];
1001        let result = C::pipeline_aware().apply(&history);
1002        assert_eq!(result.len(), 2);
1003        if let gemini_genai_rs::prelude::Part::Text { text } = &result[0].parts[0] {
1004            assert!(text.contains("Pipeline-aware"));
1005        } else {
1006            panic!("Expected text part");
1007        }
1008    }
1009}