Skip to main content

matrixcode_core/memory/
learning.rs

1//! Feedback learning and behavior inference.
2//!
3//! This module provides high-level learning mechanisms that let the model
4//! understand patterns from interactions, rather than hardcoded rules.
5
6use std::collections::HashMap;
7
8use super::config::MIN_MEMORY_CONTENT_LENGTH;
9use super::extractor::infer_category_from_content;
10use super::retrieval::extract_context_keywords;
11use super::types::{AutoMemory, MemoryCategory, MemoryEntry};
12
13// ============================================================================
14// Feedback Detection
15// ============================================================================
16
17/// Action to take when user feedback is detected.
18#[derive(Debug, Clone, PartialEq)]
19pub enum FeedbackAction {
20    Correct,
21    Delete,
22    Add,
23    NegativePreference,
24}
25
26/// Result of feedback detection.
27#[derive(Debug, Clone)]
28pub struct FeedbackResult {
29    pub action: FeedbackAction,
30    pub category: Option<MemoryCategory>,
31    pub new_content: Option<String>,
32    pub search_keywords: Vec<String>,
33    pub original_text: String,
34}
35
36/// Detect user feedback patterns - generic detection, not exhaustive.
37/// The model should use its understanding to detect nuances.
38pub fn detect_feedback_patterns(text: &str) -> Vec<FeedbackResult> {
39    let mut results = Vec::new();
40    let text_lower = text.to_lowercase();
41
42    // Generic correction signals
43    let correction_signals = ["不对", "错了", "不是", "no", "wrong", "should be"];
44    for signal in correction_signals {
45        if text_lower.contains(signal) {
46            let content = extract_feedback_content(text, signal);
47            if content.len() >= MIN_MEMORY_CONTENT_LENGTH {
48                results.push(FeedbackResult {
49                    action: FeedbackAction::Correct,
50                    category: Some(infer_category_from_content(&content)),
51                    new_content: Some(content.clone()),
52                    search_keywords: extract_context_keywords(&content),
53                    original_text: text.to_string(),
54                });
55                break; // Only one correction per message
56            }
57        }
58    }
59
60    // Generic delete signals
61    let delete_signals = ["不要", "删掉", "remove", "delete", "don't need"];
62    for signal in delete_signals {
63        if text_lower.contains(signal) {
64            let content = extract_feedback_content(text, signal);
65            results.push(FeedbackResult {
66                action: FeedbackAction::Delete,
67                category: None,
68                new_content: None,
69                search_keywords: if content.is_empty() {
70                    vec![signal.to_string()]
71                } else {
72                    extract_context_keywords(&content)
73                },
74                original_text: text.to_string(),
75            });
76            break;
77        }
78    }
79
80    // Generic add signals
81    let add_signals = ["记住", "记一下", "remember", "note"];
82    for signal in add_signals {
83        if text_lower.contains(signal) {
84            let content = extract_feedback_content(text, signal);
85            if content.len() >= MIN_MEMORY_CONTENT_LENGTH {
86                results.push(FeedbackResult {
87                    action: FeedbackAction::Add,
88                    category: Some(infer_category_from_content(&content)),
89                    new_content: Some(content),
90                    search_keywords: vec![],
91                    original_text: text.to_string(),
92                });
93                break;
94            }
95        }
96    }
97
98    // Generic negative preference signals
99    let negative_signals = ["不喜欢", "讨厌", "dislike", "hate", "don't like"];
100    for signal in negative_signals {
101        if text_lower.contains(signal) {
102            let content = extract_feedback_content(text, signal);
103            if content.len() >= MIN_MEMORY_CONTENT_LENGTH {
104                results.push(FeedbackResult {
105                    action: FeedbackAction::NegativePreference,
106                    category: Some(MemoryCategory::Preference),
107                    new_content: Some(format!("不喜欢: {}", content)),
108                    search_keywords: extract_context_keywords(&content),
109                    original_text: text.to_string(),
110                });
111                break;
112            }
113        }
114    }
115
116    results
117}
118
119fn extract_feedback_content(text: &str, pattern: &str) -> String {
120    let pos = match text.to_lowercase().find(&pattern.to_lowercase()) {
121        Some(p) => p,
122        None => return String::new(),
123    };
124
125    let start = pos + pattern.len();
126    if start >= text.len() {
127        return String::new();
128    }
129
130    let remaining = &text[start..];
131    let end = remaining
132        .find(['.', '。', '\n'])
133        .unwrap_or(remaining.len().min(100));
134
135    remaining[..end].trim().to_string()
136}
137
138/// Apply feedback to memory.
139pub fn apply_feedback_to_memory(memory: &mut AutoMemory, feedback: &FeedbackResult) -> usize {
140    let mut changes = 0;
141
142    match feedback.action {
143        FeedbackAction::Correct => {
144            if let Some(ref content) = feedback.new_content {
145                for entry in &mut memory.entries {
146                    if feedback
147                        .search_keywords
148                        .iter()
149                        .any(|k| entry.content.to_lowercase().contains(&k.to_lowercase()))
150                    {
151                        entry.content = content.clone();
152                        entry.importance = entry.importance.max(80.0);
153                        changes += 1;
154                    }
155                }
156                if changes == 0 {
157                    let category = feedback.category.unwrap_or(MemoryCategory::Finding);
158                    memory.add_memory(category, content.clone(), None);
159                    changes += 1;
160                }
161            }
162        }
163        FeedbackAction::Delete => {
164            let ids_to_delete: Vec<String> = memory
165                .entries
166                .iter()
167                .filter(|e| {
168                    feedback
169                        .search_keywords
170                        .iter()
171                        .any(|k| e.content.to_lowercase().contains(&k.to_lowercase()))
172                })
173                .take(3)
174                .map(|e| e.id.clone())
175                .collect();
176
177            for id in ids_to_delete {
178                if memory.remove(&id) {
179                    changes += 1;
180                }
181            }
182        }
183        FeedbackAction::Add => {
184            if let Some(ref content) = feedback.new_content {
185                let category = feedback.category.unwrap_or(MemoryCategory::Finding);
186                let entry = MemoryEntry::manual(category, content.clone());
187                memory.add(entry);
188                changes += 1;
189            }
190        }
191        FeedbackAction::NegativePreference => {
192            if let Some(ref content) = feedback.new_content {
193                let mut entry = MemoryEntry::manual(MemoryCategory::Preference, content.clone());
194                entry.tags.push("negative".to_string());
195                memory.add(entry);
196                changes += 1;
197            }
198        }
199    }
200
201    changes
202}
203
204// ============================================================================
205// Behavior Inference - Generic Pattern Detection
206// ============================================================================
207
208/// Configuration for behavior inference.
209#[derive(Clone)]
210pub struct BehaviorInferenceConfig {
211    pub min_occurrences: usize,
212    pub min_confidence: f64,
213    pub max_inferences: usize,
214}
215
216impl Default for BehaviorInferenceConfig {
217    fn default() -> Self {
218        Self {
219            min_occurrences: 2,
220            min_confidence: 0.6,
221            max_inferences: 5,
222        }
223    }
224}
225
226/// Result of behavior inference.
227#[derive(Debug, Clone)]
228pub struct BehaviorInference {
229    pub content: String,
230    pub confidence: f64,
231    pub occurrences: usize,
232    pub keywords: Vec<String>,
233}
234
235/// Infer patterns from behavior - generic word frequency analysis.
236/// Let the model decide what's meaningful, not hardcoded tech patterns.
237pub fn infer_preferences_from_behavior(
238    messages: &[crate::providers::Message],
239    config: &BehaviorInferenceConfig,
240) -> Vec<BehaviorInference> {
241    let user_texts: Vec<String> = messages
242        .iter()
243        .filter_map(|msg| {
244            if msg.role == crate::providers::Role::User {
245                match &msg.content {
246                    crate::providers::MessageContent::Text(t) => Some(t.clone()),
247                    crate::providers::MessageContent::Blocks(blocks) => Some(
248                        blocks
249                            .iter()
250                            .filter_map(|b| {
251                                if let crate::providers::ContentBlock::Text { text } = b {
252                                    Some(text.as_str())
253                                } else {
254                                    None
255                                }
256                            })
257                            .collect::<Vec<_>>()
258                            .join(" "),
259                    ),
260                }
261            } else {
262                None
263            }
264        })
265        .collect();
266
267    if user_texts.len() < config.min_occurrences {
268        return Vec::new();
269    }
270
271    // Generic word frequency analysis
272    let mut word_freq: HashMap<String, usize> = HashMap::new();
273    for text in &user_texts {
274        for word in text.to_lowercase().split_whitespace() {
275            if word.len() > 3 { // Skip short words
276                *word_freq.entry(word.to_string()).or_default() += 1;
277            }
278        }
279    }
280
281    // Extract high-frequency words as potential preferences
282    let inferences: Vec<BehaviorInference> = word_freq
283        .iter()
284        .filter(|(_, count)| **count >= config.min_occurrences)
285        .map(|(word, count)| {
286            let confidence = (*count as f64 / user_texts.len() as f64).min(1.0);
287            BehaviorInference {
288                content: format!("用户多次提及 '{}'", word),
289                confidence,
290                occurrences: *count,
291                keywords: vec![word.clone()],
292            }
293        })
294        .filter(|inf| inf.confidence >= config.min_confidence)
295        .take(config.max_inferences)
296        .collect();
297
298    inferences
299}
300
301/// Convert inference to memory entry.
302pub fn inference_to_memory_entry(inference: &BehaviorInference) -> MemoryEntry {
303    let mut entry = MemoryEntry::new(MemoryCategory::Preference, inference.content.clone(), None);
304    entry.importance = (inference.confidence * 70.0 + 30.0).min(80.0);
305    entry.tags = inference.keywords.clone();
306    entry
307}
308
309/// Apply behavior inferences to memory.
310pub fn apply_behavior_inferences_to_memory(
311    messages: &[crate::providers::Message],
312    memory: &mut AutoMemory,
313    config: Option<&BehaviorInferenceConfig>,
314) -> usize {
315    let cfg = config.cloned().unwrap_or_default();
316    let inferences = infer_preferences_from_behavior(messages, &cfg);
317
318    let mut added = 0;
319    for inference in inferences {
320        let entry = inference_to_memory_entry(&inference);
321        if !memory.entries.iter().any(|e| e.content == entry.content) {
322            memory.entries.push(entry);
323            added += 1;
324        }
325    }
326
327    added
328}
329
330/// Generic tool learning - let model decide what to remember.
331/// This is a placeholder for future AI-driven learning.
332pub fn apply_tool_learning_to_memory(
333    _tool_name: &str,
334    _tool_input: &serde_json::Value,
335    _tool_result: &str,
336    _is_error: bool,
337    _memory: &mut AutoMemory,
338) -> usize {
339    // Future: Use AI to analyze tool execution and extract learnings
340    // Current: Let the model handle this through its own analysis
341    0
342}