Skip to main content

graph_flow/
context.rs

1//! Context and state management for workflows.
2//!
3//! This module provides thread-safe state management across workflow tasks,
4//! including regular data storage and specialized chat history management.
5//!
6//! All `Context` methods are synchronous: the underlying storage is an
7//! in-memory map guarded by short critical sections, so there is nothing to
8//! await. Methods can be called freely from both async tasks and sync code
9//! (e.g. edge-condition closures).
10//!
11//! # Examples
12//!
13//! ## Basic Context Usage
14//!
15//! ```rust
16//! use graph_flow::Context;
17//!
18//! # fn main() -> graph_flow::Result<()> {
19//! let context = Context::new();
20//!
21//! // Store different types of data
22//! context.set("user_id", 12345)?;
23//! context.set("name", "Alice".to_string())?;
24//! context.set("active", true)?;
25//!
26//! // Retrieve data with type safety
27//! let user_id: Option<i32> = context.get("user_id");
28//! let name: Option<String> = context.get("name");
29//! let active: Option<bool> = context.get("active");
30//! # Ok(())
31//! # }
32//! ```
33//!
34//! ## Chat History Management
35//!
36//! ```rust
37//! use graph_flow::Context;
38//!
39//! let context = Context::new();
40//!
41//! // Add messages to chat history
42//! context.add_user_message("Hello, assistant!".to_string());
43//! context.add_assistant_message("Hello! How can I help you?".to_string());
44//! context.add_system_message("User session started".to_string());
45//!
46//! // Get chat history
47//! let history = context.get_chat_history();
48//! let all_messages = context.get_all_messages();
49//! let last_5 = context.get_last_messages(5);
50//!
51//! // Check history status
52//! let count = context.chat_history_len();
53//! let is_empty = context.is_chat_history_empty();
54//! ```
55//!
56//! ## Context with Message Limits
57//!
58//! ```rust
59//! use graph_flow::Context;
60//!
61//! // Create context with maximum 100 messages
62//! let context = Context::with_max_chat_messages(100);
63//!
64//! // Messages will be automatically pruned when limit is exceeded
65//! for i in 0..150 {
66//!     context.add_user_message(format!("Message {}", i));
67//! }
68//!
69//! // Only the last 100 messages are kept
70//! assert_eq!(context.chat_history_len(), 100);
71//! ```
72//!
73//! ## LLM Integration (with `rig` feature)
74//!
75//! ```rust
76//! # #[cfg(feature = "rig")]
77//! # {
78//! use graph_flow::Context;
79//!
80//! let context = Context::new();
81//!
82//! context.add_user_message("What is the capital of France?".to_string());
83//! context.add_assistant_message("The capital of France is Paris.".to_string());
84//!
85//! // Get messages in rig format for LLM calls
86//! let mut rig_messages = context.get_rig_messages();
87//! let recent_messages = context.get_last_rig_messages(10);
88//!
89//! // Use with rig-agent's completion API, whose `chat` borrows the history
90//! // mutably and appends the turn's committed messages to it:
91//! // let response = agent.chat(&user_input, &mut rig_messages).await?;
92//! # }
93//! ```
94
95use chrono::{DateTime, Utc};
96use dashmap::DashMap;
97use serde::{Deserialize, Serialize};
98use serde_json::Value;
99use std::collections::VecDeque;
100use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};
101
102use crate::error::GraphError;
103
104#[cfg(feature = "rig")]
105use rig_core::completion::Message;
106
107/// Represents the role of a message in a conversation.
108///
109/// Used in chat history to distinguish between different types of messages.
110#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
111pub enum MessageRole {
112    /// Message from a user/human
113    User,
114    /// Message from an assistant/AI
115    Assistant,
116    /// System message (instructions, status updates, etc.)
117    System,
118}
119
120/// A serializable message that can be converted to/from rig_core::completion::Message.
121///
122/// This struct provides a unified message format that can be stored, serialized,
123/// and optionally converted to other formats like rig's Message type.
124///
125/// # Examples
126///
127/// ```rust
128/// use graph_flow::{SerializableMessage, MessageRole};
129///
130/// // Create different types of messages
131/// let user_msg = SerializableMessage::user("Hello!".to_string());
132/// let assistant_msg = SerializableMessage::assistant("Hi there!".to_string());
133/// let system_msg = SerializableMessage::system("Session started".to_string());
134///
135/// // Access message properties
136/// assert_eq!(user_msg.role, MessageRole::User);
137/// assert_eq!(user_msg.content, "Hello!");
138/// ```
139#[derive(Debug, Clone, Serialize, Deserialize)]
140pub struct SerializableMessage {
141    /// The role of the message sender
142    pub role: MessageRole,
143    /// The content of the message
144    pub content: String,
145    /// When the message was created
146    pub timestamp: DateTime<Utc>,
147}
148
149impl SerializableMessage {
150    /// Create a new message with the specified role and content.
151    ///
152    /// The timestamp is automatically set to the current UTC time.
153    pub fn new(role: MessageRole, content: String) -> Self {
154        Self {
155            role,
156            content,
157            timestamp: Utc::now(),
158        }
159    }
160
161    /// Create a new user message.
162    pub fn user(content: String) -> Self {
163        Self::new(MessageRole::User, content)
164    }
165
166    /// Create a new assistant message.
167    pub fn assistant(content: String) -> Self {
168        Self::new(MessageRole::Assistant, content)
169    }
170
171    /// Create a new system message.
172    pub fn system(content: String) -> Self {
173        Self::new(MessageRole::System, content)
174    }
175}
176
177/// Container for managing chat history with serialization support.
178///
179/// Messages are stored in a ring buffer: when the configured limit is
180/// exceeded, the oldest message is dropped in O(1).
181///
182/// # Examples
183///
184/// ```rust
185/// use graph_flow::ChatHistory;
186///
187/// let mut history = ChatHistory::new();
188/// history.add_user_message("Hello".to_string());
189/// history.add_assistant_message("Hi there!".to_string());
190///
191/// assert_eq!(history.len(), 2);
192/// assert!(!history.is_empty());
193///
194/// let contents: Vec<&str> = history.messages().map(|m| m.content.as_str()).collect();
195/// assert_eq!(contents, ["Hello", "Hi there!"]);
196/// ```
197#[derive(Debug, Clone, Serialize, Deserialize, Default)]
198pub struct ChatHistory {
199    messages: VecDeque<SerializableMessage>,
200    max_messages: Option<usize>,
201}
202
203impl ChatHistory {
204    /// Create a new empty chat history with a default limit of 1000 messages.
205    pub fn new() -> Self {
206        Self {
207            messages: VecDeque::new(),
208            max_messages: Some(1000), // Default limit to prevent unbounded growth
209        }
210    }
211
212    /// Create a new chat history with a maximum message limit.
213    ///
214    /// When the limit is exceeded, older messages are automatically removed.
215    ///
216    /// # Examples
217    ///
218    /// ```rust
219    /// use graph_flow::ChatHistory;
220    ///
221    /// let mut history = ChatHistory::with_max_messages(10);
222    ///
223    /// for i in 0..15 {
224    ///     history.add_user_message(format!("Message {}", i));
225    /// }
226    ///
227    /// // Only the last 10 are kept
228    /// assert_eq!(history.len(), 10);
229    /// ```
230    pub fn with_max_messages(max: usize) -> Self {
231        Self {
232            messages: VecDeque::new(),
233            max_messages: Some(max),
234        }
235    }
236
237    /// Add a user message to the chat history.
238    pub fn add_user_message(&mut self, content: String) {
239        self.add_message(SerializableMessage::user(content));
240    }
241
242    /// Add an assistant message to the chat history.
243    pub fn add_assistant_message(&mut self, content: String) {
244        self.add_message(SerializableMessage::assistant(content));
245    }
246
247    /// Add a system message to the chat history.
248    pub fn add_system_message(&mut self, content: String) {
249        self.add_message(SerializableMessage::system(content));
250    }
251
252    /// Add a message to the chat history, respecting max_messages limit.
253    fn add_message(&mut self, message: SerializableMessage) {
254        self.messages.push_back(message);
255
256        if let Some(max) = self.max_messages {
257            while self.messages.len() > max {
258                self.messages.pop_front();
259            }
260        }
261    }
262
263    /// Clear all messages from the chat history.
264    pub fn clear(&mut self) {
265        self.messages.clear();
266    }
267
268    /// Get the number of messages in the chat history.
269    pub fn len(&self) -> usize {
270        self.messages.len()
271    }
272
273    /// Check if the chat history is empty.
274    pub fn is_empty(&self) -> bool {
275        self.messages.is_empty()
276    }
277
278    /// Iterate over all messages, oldest first.
279    pub fn messages(&self) -> impl Iterator<Item = &SerializableMessage> + '_ {
280        self.messages.iter()
281    }
282
283    /// Iterate over the last N messages, oldest first.
284    ///
285    /// If N is greater than the total number of messages, all messages are returned.
286    ///
287    /// # Examples
288    ///
289    /// ```rust
290    /// use graph_flow::ChatHistory;
291    ///
292    /// let mut history = ChatHistory::new();
293    /// history.add_user_message("Message 1".to_string());
294    /// history.add_user_message("Message 2".to_string());
295    /// history.add_user_message("Message 3".to_string());
296    ///
297    /// let last_two: Vec<&str> = history.last_messages(2).map(|m| m.content.as_str()).collect();
298    /// assert_eq!(last_two, ["Message 2", "Message 3"]);
299    /// ```
300    pub fn last_messages(&self, n: usize) -> impl Iterator<Item = &SerializableMessage> + '_ {
301        self.messages
302            .iter()
303            .skip(self.messages.len().saturating_sub(n))
304    }
305}
306
307/// Helper struct for serializing/deserializing Context
308#[derive(Serialize, Deserialize)]
309struct ContextData {
310    data: std::collections::HashMap<String, Value>,
311    chat_history: ChatHistory,
312}
313
314/// Context for sharing data between tasks in a graph execution.
315///
316/// Provides thread-safe storage for workflow state and dedicated chat history
317/// management. The context is shared across all tasks in a workflow execution
318/// (cloning a `Context` is cheap and yields a handle to the same state).
319///
320/// All methods are synchronous - see the [module docs](self) for rationale.
321///
322/// # Examples
323///
324/// ```rust
325/// use graph_flow::Context;
326///
327/// # fn main() -> graph_flow::Result<()> {
328/// let context = Context::new();
329///
330/// // Typed key-value state
331/// context.set("user_id", 12345)?;
332/// let user_id: Option<i32> = context.get("user_id");
333///
334/// // Chat history
335/// context.add_user_message("Hello".to_string());
336/// let history = context.get_chat_history();
337/// # Ok(())
338/// # }
339/// ```
340#[derive(Clone, Debug)]
341pub struct Context {
342    data: Arc<DashMap<String, Value>>,
343    chat_history: Arc<RwLock<ChatHistory>>,
344}
345
346impl Context {
347    /// Create a new empty context.
348    pub fn new() -> Self {
349        Self {
350            data: Arc::new(DashMap::new()),
351            chat_history: Arc::new(RwLock::new(ChatHistory::new())),
352        }
353    }
354
355    /// Create a new context with a maximum chat history size.
356    ///
357    /// When the chat history exceeds this size, older messages are automatically removed.
358    pub fn with_max_chat_messages(max: usize) -> Self {
359        Self {
360            data: Arc::new(DashMap::new()),
361            chat_history: Arc::new(RwLock::new(ChatHistory::with_max_messages(max))),
362        }
363    }
364
365    /// Acquire the chat history read lock, recovering from poisoning.
366    ///
367    /// A poisoned lock means a task panicked while holding it; the history
368    /// itself is still valid (messages are appended atomically), so we recover
369    /// the guard rather than silently returning empty data.
370    fn history_read(&self) -> RwLockReadGuard<'_, ChatHistory> {
371        self.chat_history
372            .read()
373            .unwrap_or_else(|poisoned| poisoned.into_inner())
374    }
375
376    /// Acquire the chat history write lock, recovering from poisoning (see
377    /// [`Context::history_read`]).
378    fn history_write(&self) -> RwLockWriteGuard<'_, ChatHistory> {
379        self.chat_history
380            .write()
381            .unwrap_or_else(|poisoned| poisoned.into_inner())
382    }
383
384    // Regular context methods
385
386    /// Set a value in the context.
387    ///
388    /// Returns `Err(GraphError::ContextError)` if the value cannot be
389    /// serialized to JSON (e.g. a map with non-string keys).
390    ///
391    /// # Examples
392    ///
393    /// ```rust
394    /// use graph_flow::Context;
395    /// use serde::{Serialize, Deserialize};
396    ///
397    /// #[derive(Serialize, Deserialize)]
398    /// struct UserData {
399    ///     id: u32,
400    ///     name: String,
401    /// }
402    ///
403    /// # fn main() -> graph_flow::Result<()> {
404    /// let context = Context::new();
405    ///
406    /// // Store primitive types
407    /// context.set("count", 42)?;
408    /// context.set("name", "Alice".to_string())?;
409    ///
410    /// // Store complex types
411    /// let user = UserData { id: 1, name: "Bob".to_string() };
412    /// context.set("user", user)?;
413    /// # Ok(())
414    /// # }
415    /// ```
416    pub fn set(&self, key: impl Into<String>, value: impl serde::Serialize) -> crate::error::Result<()> {
417        let key = key.into();
418        let value = serde_json::to_value(value).map_err(|e| {
419            GraphError::ContextError(format!("Failed to serialize value for key '{key}': {e}"))
420        })?;
421        self.data.insert(key, value);
422        Ok(())
423    }
424
425    /// Get a value from the context.
426    ///
427    /// Returns `None` if the key doesn't exist or if the stored value cannot
428    /// be deserialized to the requested type (a warning is logged for the
429    /// latter, since it usually indicates a type mismatch bug).
430    ///
431    /// # Examples
432    ///
433    /// ```rust
434    /// use graph_flow::Context;
435    ///
436    /// # fn main() -> graph_flow::Result<()> {
437    /// let context = Context::new();
438    /// context.set("count", 42)?;
439    ///
440    /// let count: Option<i32> = context.get("count");
441    /// assert_eq!(count, Some(42));
442    ///
443    /// let missing: Option<String> = context.get("missing");
444    /// assert_eq!(missing, None);
445    /// # Ok(())
446    /// # }
447    /// ```
448    pub fn get<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
449        let entry = self.data.get(key)?;
450        // Deserialize straight from a reference to avoid cloning the stored
451        // Value (which can be large, e.g. documents or chat transcripts).
452        match T::deserialize(entry.value()) {
453            Ok(value) => Some(value),
454            Err(e) => {
455                tracing::warn!(
456                    key = %key,
457                    error = %e,
458                    "Context value exists but failed to deserialize to the requested type"
459                );
460                None
461            }
462        }
463    }
464
465    /// Remove a value from the context.
466    ///
467    /// Returns the removed value if it existed.
468    pub fn remove(&self, key: &str) -> Option<Value> {
469        self.data.remove(key).map(|(_, v)| v)
470    }
471
472    /// Clear all regular context data (does not affect chat history).
473    pub fn clear(&self) {
474        self.data.clear();
475    }
476
477    // Chat history methods
478
479    /// Add a user message to the chat history.
480    pub fn add_user_message(&self, content: String) {
481        self.history_write().add_user_message(content);
482    }
483
484    /// Add an assistant message to the chat history.
485    pub fn add_assistant_message(&self, content: String) {
486        self.history_write().add_assistant_message(content);
487    }
488
489    /// Add a system message to the chat history.
490    pub fn add_system_message(&self, content: String) {
491        self.history_write().add_system_message(content);
492    }
493
494    /// Get a clone of the current chat history.
495    pub fn get_chat_history(&self) -> ChatHistory {
496        self.history_read().clone()
497    }
498
499    /// Clear the chat history.
500    pub fn clear_chat_history(&self) {
501        self.history_write().clear();
502    }
503
504    /// Get the number of messages in the chat history.
505    pub fn chat_history_len(&self) -> usize {
506        self.history_read().len()
507    }
508
509    /// Check if the chat history is empty.
510    pub fn is_chat_history_empty(&self) -> bool {
511        self.history_read().is_empty()
512    }
513
514    /// Get the last N messages from chat history, oldest first.
515    pub fn get_last_messages(&self, n: usize) -> Vec<SerializableMessage> {
516        self.history_read().last_messages(n).cloned().collect()
517    }
518
519    /// Get all messages from chat history, oldest first.
520    pub fn get_all_messages(&self) -> Vec<SerializableMessage> {
521        self.history_read().messages().cloned().collect()
522    }
523
524    // Rig integration methods (only available when rig feature is enabled)
525
526    #[cfg(feature = "rig")]
527    /// Get all chat history messages converted to rig_core::completion::Message format.
528    ///
529    /// This method is only available when the "rig" feature is enabled.
530    pub fn get_rig_messages(&self) -> Vec<Message> {
531        self.get_all_messages().into_iter().map(Message::from).collect()
532    }
533
534    #[cfg(feature = "rig")]
535    /// Get the last N messages converted to rig_core::completion::Message format.
536    ///
537    /// This method is only available when the "rig" feature is enabled.
538    pub fn get_last_rig_messages(&self, n: usize) -> Vec<Message> {
539        self.get_last_messages(n).into_iter().map(Message::from).collect()
540    }
541}
542
543#[cfg(feature = "rig")]
544impl From<SerializableMessage> for Message {
545    /// Convert a [`SerializableMessage`] into a `rig_core::completion::Message`,
546    /// moving the content instead of cloning it.
547    ///
548    /// Only available when the "rig" feature is enabled.
549    fn from(msg: SerializableMessage) -> Self {
550        match msg.role {
551            MessageRole::User => Message::user(msg.content),
552            MessageRole::Assistant => Message::assistant(msg.content),
553            MessageRole::System => Message::system(msg.content),
554        }
555    }
556}
557
558impl Default for Context {
559    fn default() -> Self {
560        Self::new()
561    }
562}
563
564// Serialization support for Context
565impl Serialize for Context {
566    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
567    where
568        S: serde::Serializer,
569    {
570        // Convert DashMap to HashMap for serialization
571        let data: std::collections::HashMap<String, Value> = self
572            .data
573            .iter()
574            .map(|entry| (entry.key().clone(), entry.value().clone()))
575            .collect();
576
577        let chat_history = self.history_read().clone();
578
579        let context_data = ContextData { data, chat_history };
580        context_data.serialize(serializer)
581    }
582}
583
584impl<'de> Deserialize<'de> for Context {
585    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
586    where
587        D: serde::Deserializer<'de>,
588    {
589        let context_data = ContextData::deserialize(deserializer)?;
590
591        let data = Arc::new(DashMap::new());
592        for (key, value) in context_data.data {
593            data.insert(key, value);
594        }
595
596        let chat_history = Arc::new(RwLock::new(context_data.chat_history));
597
598        Ok(Context { data, chat_history })
599    }
600}
601
602#[cfg(test)]
603mod tests {
604    use super::*;
605
606    #[test]
607    fn test_basic_context_operations() {
608        let context = Context::new();
609
610        context.set("key", "value").unwrap();
611        let value: Option<String> = context.get("key");
612        assert_eq!(value, Some("value".to_string()));
613    }
614
615    #[test]
616    fn test_set_unserializable_value_errors() {
617        use std::collections::HashMap;
618        let context = Context::new();
619
620        // Maps with non-string keys cannot be represented in JSON
621        let bad: HashMap<Vec<u8>, String> = HashMap::from([(vec![1u8], "x".to_string())]);
622        assert!(context.set("bad", bad).is_err());
623    }
624
625    #[test]
626    fn test_chat_history_operations() {
627        let context = Context::new();
628
629        assert!(context.is_chat_history_empty());
630        assert_eq!(context.chat_history_len(), 0);
631
632        context.add_user_message("Hello".to_string());
633        context.add_assistant_message("Hi there!".to_string());
634
635        assert!(!context.is_chat_history_empty());
636        assert_eq!(context.chat_history_len(), 2);
637
638        let history = context.get_chat_history();
639        assert_eq!(history.len(), 2);
640        let messages: Vec<_> = history.messages().collect();
641        assert_eq!(messages[0].content, "Hello");
642        assert_eq!(messages[0].role, MessageRole::User);
643        assert_eq!(messages[1].content, "Hi there!");
644        assert_eq!(messages[1].role, MessageRole::Assistant);
645    }
646
647    #[test]
648    fn test_chat_history_max_messages() {
649        let context = Context::with_max_chat_messages(2);
650
651        context.add_user_message("Message 1".to_string());
652        context.add_assistant_message("Response 1".to_string());
653        context.add_user_message("Message 2".to_string());
654
655        let history = context.get_chat_history();
656        assert_eq!(history.len(), 2);
657        let messages: Vec<_> = history.messages().collect();
658        assert_eq!(messages[0].content, "Response 1");
659        assert_eq!(messages[1].content, "Message 2");
660    }
661
662    #[test]
663    fn test_last_messages() {
664        let context = Context::new();
665
666        context.add_user_message("Message 1".to_string());
667        context.add_assistant_message("Response 1".to_string());
668        context.add_user_message("Message 2".to_string());
669        context.add_assistant_message("Response 2".to_string());
670
671        let last_two = context.get_last_messages(2);
672        assert_eq!(last_two.len(), 2);
673        assert_eq!(last_two[0].content, "Message 2");
674        assert_eq!(last_two[1].content, "Response 2");
675    }
676
677    #[test]
678    fn test_context_serialization() {
679        let context = Context::new();
680        context.set("key", "value").unwrap();
681        context.add_user_message("test message".to_string());
682
683        let serialized = serde_json::to_string(&context).unwrap();
684        let deserialized: Context = serde_json::from_str(&serialized).unwrap();
685
686        let value: Option<String> = deserialized.get("key");
687        assert_eq!(value, Some("value".to_string()));
688
689        assert_eq!(deserialized.chat_history_len(), 1);
690        let history = deserialized.get_chat_history();
691        let first = history.messages().next().unwrap();
692        assert_eq!(first.content, "test message");
693        assert_eq!(first.role, MessageRole::User);
694    }
695
696    #[test]
697    fn test_serializable_message() {
698        let msg = SerializableMessage::user("test content".to_string());
699        assert_eq!(msg.role, MessageRole::User);
700        assert_eq!(msg.content, "test content");
701
702        let serialized = serde_json::to_string(&msg).unwrap();
703        let deserialized: SerializableMessage = serde_json::from_str(&serialized).unwrap();
704
705        assert_eq!(msg.role, deserialized.role);
706        assert_eq!(msg.content, deserialized.content);
707    }
708
709    #[test]
710    fn test_chat_history_serialization() {
711        let mut history = ChatHistory::new();
712        history.add_user_message("Hello".to_string());
713        history.add_assistant_message("Hi!".to_string());
714
715        let serialized = serde_json::to_string(&history).unwrap();
716        let deserialized: ChatHistory = serde_json::from_str(&serialized).unwrap();
717
718        assert_eq!(deserialized.len(), 2);
719        let messages: Vec<_> = deserialized.messages().collect();
720        assert_eq!(messages[0].content, "Hello");
721        assert_eq!(messages[1].content, "Hi!");
722    }
723
724    #[test]
725    fn test_chat_history_json_compat_with_0_5() {
726        // 0.5 serialized `messages` as a JSON array from a Vec; the VecDeque
727        // representation must remain interchangeable.
728        let json = r#"{"messages":[{"role":"User","content":"hi","timestamp":"2026-01-01T00:00:00Z"}],"max_messages":1000}"#;
729        let history: ChatHistory = serde_json::from_str(json).unwrap();
730        assert_eq!(history.len(), 1);
731    }
732
733    #[cfg(feature = "rig")]
734    #[test]
735    fn test_rig_integration() {
736        let context = Context::new();
737
738        context.add_user_message("Hello".to_string());
739        context.add_assistant_message("Hi there!".to_string());
740        context.add_system_message("System message".to_string());
741
742        let rig_messages = context.get_rig_messages();
743        assert_eq!(rig_messages.len(), 3);
744
745        // Verify each message maps to the correct rig variant.
746        assert!(
747            matches!(&rig_messages[0], Message::User { .. }),
748            "Expected Message::User, got: {:?}",
749            rig_messages[0]
750        );
751        assert!(
752            matches!(&rig_messages[1], Message::Assistant { .. }),
753            "Expected Message::Assistant, got: {:?}",
754            rig_messages[1]
755        );
756        assert!(
757            matches!(&rig_messages[2], Message::System { content } if content == "System message"),
758            "Expected Message::System with correct content, got: {:?}",
759            rig_messages[2]
760        );
761
762        // Verify get_last_rig_messages tail ordering when the tail includes a system message.
763        let last_two = context.get_last_rig_messages(2);
764        assert_eq!(last_two.len(), 2);
765        assert!(
766            matches!(&last_two[0], Message::Assistant { .. }),
767            "Expected Message::Assistant as second-to-last, got: {:?}",
768            last_two[0]
769        );
770        assert!(
771            matches!(&last_two[1], Message::System { .. }),
772            "Expected Message::System as last, got: {:?}",
773            last_two[1]
774        );
775    }
776}