Skip to main content

oxios_kernel/space/
conversation_buffer.rs

1//! ConversationBuffer: in-memory circular buffer of recent conversation turns.
2//!
3//! Used by SpaceManager for topic shift detection. Maintains recent N turns
4//! in memory (not persisted — restarts with empty buffer, which is fine since
5//! Layer 1/2 detection doesn't need history).
6
7use chrono::{DateTime, Utc};
8use serde::{Deserialize, Serialize};
9use std::collections::VecDeque;
10
11use super::SpaceId;
12
13/// A single conversation turn (user message + agent response).
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct ConversationTurn {
16    /// User message.
17    pub user: String,
18    /// Agent response (truncated to first 200 chars for efficiency).
19    pub agent: String,
20    /// Active Space at the time.
21    pub space_id: SpaceId,
22    /// Timestamp.
23    pub timestamp: DateTime<Utc>,
24}
25
26/// In-memory circular buffer of recent conversation turns.
27#[derive(Debug, Clone)]
28pub struct ConversationBuffer {
29    /// Recent turns (bounded, oldest evicted first).
30    turns: VecDeque<ConversationTurn>,
31    /// Maximum number of turns to retain.
32    max_turns: usize,
33    /// Counter for topic check frequency limiting.
34    turns_since_topic_check: usize,
35    /// Last observed Space ID (for tracking Space switches).
36    last_space_id: Option<SpaceId>,
37}
38
39impl Default for ConversationBuffer {
40    fn default() -> Self {
41        Self::new(50)
42    }
43}
44
45impl ConversationBuffer {
46    /// Create a new buffer with the given maximum size.
47    pub fn new(max_turns: usize) -> Self {
48        Self {
49            turns: VecDeque::with_capacity(max_turns),
50            max_turns,
51            turns_since_topic_check: 0,
52            last_space_id: None,
53        }
54    }
55
56    /// Record a user message (before processing).
57    pub fn push_user(&mut self, message: &str) {
58        let turn = ConversationTurn {
59            user: message.to_string(),
60            agent: String::new(),     // filled later by push_agent
61            space_id: SpaceId::nil(), // filled later
62            timestamp: Utc::now(),
63        };
64
65        // If last turn has empty agent, it's the pending turn — replace
66        if let Some(last) = self.turns.back_mut() {
67            if last.agent.is_empty() && last.space_id == SpaceId::nil() {
68                last.user = message.to_string();
69                last.timestamp = Utc::now();
70                return;
71            }
72        }
73
74        self.turns.push_back(turn);
75
76        // Evict oldest if over capacity
77        while self.turns.len() > self.max_turns {
78            self.turns.pop_front();
79        }
80    }
81
82    /// Record an agent response and Space (call after processing completes).
83    pub fn push_agent(&mut self, response: &str, space_id: &SpaceId) {
84        if let Some(last) = self.turns.back_mut() {
85            last.agent = truncate_response(response, 200);
86            last.space_id = *space_id;
87            self.last_space_id = Some(*space_id);
88        }
89    }
90
91    /// Get the most recent N turns.
92    pub fn recent(&self, n: usize) -> Vec<&ConversationTurn> {
93        self.turns.iter().rev().take(n).collect()
94    }
95
96    /// Get all turns.
97    pub fn turns(&self) -> std::collections::VecDeque<ConversationTurn> {
98        self.turns.clone()
99    }
100
101    /// Get the total number of turns.
102    pub fn len(&self) -> usize {
103        self.turns.len()
104    }
105
106    /// Check if the buffer is empty.
107    pub fn is_empty(&self) -> bool {
108        self.turns.is_empty()
109    }
110
111    /// Check if topic shift detection should run.
112    ///
113    /// Returns true if N or more turns have passed since the last check,
114    /// or if the conversation pattern has visibly changed.
115    pub fn should_check_topic(&self, min_turns: usize) -> bool {
116        self.turns_since_topic_check >= min_turns || self.pattern_changed()
117    }
118
119    /// Record that a topic check was performed.
120    pub fn mark_topic_checked(&mut self) {
121        self.turns_since_topic_check = 0;
122    }
123
124    /// Increment the turn counter and check if topic check should run.
125    pub fn record_turn(&mut self, min_turns: usize) -> bool {
126        self.turns_since_topic_check += 1;
127        self.should_check_topic(min_turns)
128    }
129
130    /// Detect if the conversation pattern has changed.
131    ///
132    /// Looks at average word count and average message length to detect
133    /// topic or style shifts without LLM.
134    pub fn pattern_changed(&self) -> bool {
135        if self.turns.len() < 4 {
136            return false;
137        }
138
139        let all_turns: Vec<_> = self.turns.iter().collect();
140
141        // Compare recent 2 turns vs previous 2 turns
142        let recent = &all_turns[all_turns.len() - 2..];
143        let previous = &all_turns[all_turns.len() - 4..all_turns.len() - 2];
144
145        let avg_word_count_recent =
146            recent.iter().map(|t| word_count(&t.user)).sum::<usize>() as f64 / recent.len() as f64;
147
148        let avg_word_count_prev = previous.iter().map(|t| word_count(&t.user)).sum::<usize>()
149            as f64
150            / previous.len() as f64;
151
152        // If average word count changed by more than 50%, consider it a pattern change
153        let ratio = avg_word_count_recent / avg_word_count_prev.max(1.0);
154        if !(0.5..=2.0).contains(&ratio) {
155            return true;
156        }
157
158        // Check for domain-specific keywords that suggest topic shift
159        let domain_shift_keywords = [
160            ("code", "food"),
161            ("rust", "요리"),
162            ("bug", "저녁"),
163            ("file", "운동"),
164            ("import", "영화"),
165            ("commit", "음식"),
166            ("function", "게임"),
167            ("Cargo", "장보기"),
168        ];
169
170        let recent_text = recent
171            .iter()
172            .map(|t| t.user.to_lowercase())
173            .collect::<String>();
174        let prev_text = previous
175            .iter()
176            .map(|t| t.user.to_lowercase())
177            .collect::<String>();
178
179        for (prev_kw, recent_kw) in domain_shift_keywords {
180            let has_prev = prev_text.contains(prev_kw);
181            let has_recent = recent_text.contains(recent_kw);
182            if has_prev && !has_recent {
183                // Keyword disappeared — possible topic shift
184                // But we need to be in the same Space still
185                return true;
186            }
187        }
188
189        false
190    }
191
192    /// Check if the Space has changed since the last turn.
193    pub fn space_changed(&self) -> bool {
194        if self.turns.len() < 2 {
195            return false;
196        }
197
198        let all_turns: Vec<_> = self.turns.iter().collect();
199        let last = &all_turns[all_turns.len() - 1];
200        let prev = &all_turns[all_turns.len() - 2];
201
202        last.space_id != prev.space_id
203    }
204
205    /// Get the last recorded Space ID.
206    pub fn last_space_id(&self) -> Option<SpaceId> {
207        self.last_space_id
208    }
209
210    /// Clear all turns.
211    pub fn clear(&mut self) {
212        self.turns.clear();
213        self.turns_since_topic_check = 0;
214    }
215}
216
217/// Count words in a string.
218fn word_count(s: &str) -> usize {
219    s.split_whitespace().count()
220}
221
222/// Truncate response to max_len chars.
223fn truncate_response(response: &str, max_len: usize) -> String {
224    if response.len() <= max_len {
225        response.to_string()
226    } else {
227        format!("{}...", &response[..max_len])
228    }
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    #[test]
236    fn test_push_user_and_agent() {
237        let mut buf = ConversationBuffer::new(10);
238        assert!(buf.is_empty());
239
240        buf.push_user("Hello, how are you?");
241        assert_eq!(buf.len(), 1);
242        assert_eq!(buf.turns[0].user, "Hello, how are you?");
243        assert!(buf.turns[0].agent.is_empty());
244
245        buf.push_agent("I'm doing well!", &SpaceId::nil());
246        assert_eq!(buf.turns[0].agent, "I'm doing well!");
247    }
248
249    #[test]
250    fn test_max_capacity() {
251        let mut buf = ConversationBuffer::new(3);
252        let space = SpaceId::nil();
253
254        buf.push_user("msg1");
255        buf.push_agent("r1", &space);
256        buf.push_user("msg2");
257        buf.push_agent("r2", &space);
258        buf.push_user("msg3");
259        buf.push_agent("r3", &space);
260        buf.push_user("msg4");
261        buf.push_agent("r4", &space);
262        buf.push_user("msg5");
263        buf.push_agent("r5", &space);
264
265        // Oldest should be evicted
266        assert_eq!(buf.len(), 3);
267        assert_eq!(buf.recent(1)[0].user, "msg5");
268    }
269
270    #[test]
271    fn test_should_check_topic() {
272        let mut buf = ConversationBuffer::new(10);
273        assert!(!buf.should_check_topic(3));
274
275        for _ in 0..3 {
276            buf.push_user("test");
277            buf.mark_topic_checked();
278        }
279        // After mark_topic_checked, counter resets
280        assert!(!buf.should_check_topic(3));
281    }
282
283    #[test]
284    fn test_pattern_changed_word_count() {
285        let mut buf = ConversationBuffer::new(10);
286        let space = SpaceId::nil();
287
288        // Short messages
289        for _ in 0..3 {
290            buf.push_user("hi");
291            buf.push_agent("hi", &space);
292        }
293
294        assert!(!buf.pattern_changed());
295
296        // Now a very long message
297        buf.push_user("This is a very long message that contains many many many many many words to trigger the pattern detection");
298        buf.push_agent("ok", &space);
299
300        assert!(buf.pattern_changed());
301    }
302
303    #[test]
304    fn test_truncate_response() {
305        let short = "Hello";
306        assert_eq!(truncate_response(short, 10), "Hello");
307
308        let long = "This is a very long response";
309        let truncated = truncate_response(long, 10);
310        assert_eq!(truncated.len(), 13); // 10 + "..."
311        assert!(truncated.ends_with("..."));
312    }
313
314    #[test]
315    fn test_recent_turns() {
316        let mut buf = ConversationBuffer::new(10);
317        let space = SpaceId::nil();
318
319        for i in 0..5 {
320            buf.push_user(&format!("msg{}", i));
321            buf.push_agent(&format!("resp{}", i), &space);
322        }
323
324        let recent = buf.recent(3);
325        assert_eq!(recent.len(), 3);
326        assert_eq!(recent[0].user, "msg4"); // most recent first
327        assert_eq!(recent[2].user, "msg2");
328    }
329}