1use std::sync::LazyLock;
7
8use async_trait::async_trait;
9use chrono::{DateTime, Utc};
10use regex::Regex;
11use serde::{Deserialize, Serialize};
12use tracing::{info, warn};
13
14use crate::embed::Embedder;
15use crate::error::{MemoryError, Result};
16
17#[derive(Debug, Clone, Serialize, Deserialize, Default)]
19pub struct UserProfile {
20 pub id: i64,
21 pub verbosity_preference: String, pub explanation_depth: String, pub tone_preference: String, pub emoji_preference: String, #[serde(skip_serializing_if = "Option::is_none")]
26 pub typical_session_length: Option<i32>,
27 #[serde(skip_serializing_if = "Option::is_none")]
28 pub active_hours: Option<Vec<i32>>,
29 #[serde(skip_serializing_if = "Option::is_none")]
30 pub common_workflows: Option<Vec<String>>,
31 pub asks_before_acting: bool,
32 pub prefers_explanations: bool,
33 pub likes_suggestions: bool,
34 pub updated_at: DateTime<Utc>,
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct BehaviorPattern {
40 pub id: i64,
41 pub pattern_type: String, pub description: String,
43 #[serde(skip_serializing_if = "Option::is_none")]
44 pub trigger_context: Option<String>,
45 #[serde(skip_serializing_if = "Option::is_none")]
46 pub action: Option<String>,
47 pub confidence: f32,
48 pub occurrence_count: i32,
49 #[serde(skip_serializing_if = "Option::is_none")]
50 pub last_seen_at: Option<DateTime<Utc>>,
51 pub created_at: DateTime<Utc>,
52}
53
54#[derive(Debug, Clone, Serialize, Deserialize)]
56pub struct Procedure {
57 pub id: i64,
58 pub name: String,
59 pub trigger_pattern: String,
60 pub steps: Vec<String>,
61 pub success_count: i32,
62 pub failure_count: i32,
63 #[serde(skip_serializing_if = "Option::is_none")]
64 pub avg_duration_secs: Option<f32>,
65 #[serde(skip_serializing_if = "Option::is_none")]
66 pub last_used_at: Option<DateTime<Utc>>,
67 pub created_at: DateTime<Utc>,
68 pub updated_at: DateTime<Utc>,
69}
70
71#[derive(Debug, Clone, Serialize, Deserialize)]
73pub struct Expertise {
74 pub id: i64,
75 pub domain: String,
76 pub tasks_attempted: i32,
77 pub tasks_succeeded: i32,
78 pub tasks_failed: i32,
79 pub current_level: String, pub confidence_score: f32,
81 #[serde(skip_serializing_if = "Option::is_none")]
82 pub common_errors: Option<Vec<String>>,
83 #[serde(skip_serializing_if = "Option::is_none")]
84 pub last_task_at: Option<DateTime<Utc>>,
85 pub created_at: DateTime<Utc>,
86 pub updated_at: DateTime<Utc>,
87}
88
89#[derive(Debug, Clone, Serialize, Deserialize)]
91pub struct ErrorSolution {
92 pub id: i64,
93 pub error_pattern: String,
94 #[serde(skip_serializing_if = "Option::is_none")]
95 pub domain: Option<String>,
96 pub solution_summary: String,
97 #[serde(skip_serializing_if = "Option::is_none")]
98 pub solution_steps: Option<Vec<String>>,
99 pub success_count: i32,
100 pub failure_count: i32,
101 #[serde(skip_serializing_if = "Option::is_none")]
102 pub last_used_at: Option<DateTime<Utc>>,
103 pub created_at: DateTime<Utc>,
104}
105
106#[async_trait]
108pub trait LearningStore: Send + Sync {
109 async fn get_behavior_patterns(&self, _min_confidence: f32) -> Result<Vec<BehaviorPattern>> {
111 Ok(vec![])
112 }
113
114 async fn record_behavior_pattern(
116 &self,
117 _pattern_type: &str,
118 _description: &str,
119 _trigger_context: Option<&str>,
120 _action: Option<&str>,
121 _confidence_hint: f32,
122 _occurrence_delta: i32,
123 ) -> Result<()> {
124 Ok(())
125 }
126
127 async fn get_relevant_procedures(&self, _query: &str, _limit: usize) -> Result<Vec<Procedure>> {
129 Ok(vec![])
130 }
131
132 async fn get_relevant_error_solutions(
134 &self,
135 _error: &str,
136 _limit: usize,
137 ) -> Result<Vec<ErrorSolution>> {
138 Ok(vec![])
139 }
140
141 async fn get_user_profile(&self) -> Result<Option<UserProfile>> {
143 Ok(None)
144 }
145
146 async fn update_user_profile(&self, _profile: &UserProfile) -> Result<()> {
148 Ok(())
149 }
150
151 async fn increment_expertise(
153 &self,
154 _domain: &str,
155 _success: bool,
156 _error: Option<&str>,
157 ) -> Result<()> {
158 Ok(())
159 }
160
161 async fn upsert_procedure(&self, _procedure: &Procedure) -> Result<i64> {
163 Ok(0)
164 }
165
166 #[allow(dead_code)] async fn update_procedure_outcome(
169 &self,
170 _procedure_id: i64,
171 _success: bool,
172 _duration: Option<f32>,
173 ) -> Result<()> {
174 Ok(())
175 }
176
177 async fn insert_error_solution(&self, _solution: &ErrorSolution) -> Result<i64> {
179 Ok(0)
180 }
181
182 #[allow(dead_code)] async fn update_error_solution_outcome(&self, _solution_id: i64, _success: bool) -> Result<()> {
185 Ok(())
186 }
187
188 async fn record_procedure_observation(&self, procedure: &Procedure) -> Result<()> {
193 self.upsert_procedure(procedure).await.map(|_| ())
194 }
195
196 async fn record_error_solution_observation(&self, solution: &ErrorSolution) -> Result<()> {
199 self.insert_error_solution(solution).await.map(|_| ())
200 }
201
202 async fn record_task_outcome(&self, domain: &str, success: bool) -> Result<()> {
206 self.increment_expertise(domain, success, None).await
207 }
208
209 async fn procedure_trigger_embeddings(&self) -> Result<Vec<Vec<f32>>> {
211 Ok(vec![])
212 }
213
214 async fn set_procedure_trigger_embedding(&self, _name: &str, _embedding: &[f32]) -> Result<()> {
216 Ok(())
217 }
218
219 async fn procedures_missing_embedding(&self, _limit: usize) -> Result<Vec<(i64, String)>> {
221 Ok(vec![])
222 }
223
224 async fn save_procedure_embedding(
226 &self,
227 _id: i64,
228 _trigger: &str,
229 _embedding: Vec<f32>,
230 ) -> Result<()> {
231 Ok(())
232 }
233
234 async fn error_solutions_missing_embedding(&self, _limit: usize) -> Result<Vec<(i64, String)>> {
236 Ok(vec![])
237 }
238
239 async fn save_error_solution_embedding(
241 &self,
242 _id: i64,
243 _pattern: &str,
244 _embedding: Vec<f32>,
245 ) -> Result<()> {
246 Ok(())
247 }
248}
249
250const EMBEDDING_BACKFILL_BATCH: usize = 10;
252
253pub async fn backfill_learning_embeddings<S>(store: &S, embedder: &dyn Embedder) -> Result<bool>
256where
257 S: LearningStore + ?Sized,
258{
259 let procedures = store
260 .procedures_missing_embedding(EMBEDDING_BACKFILL_BATCH)
261 .await?;
262 if !procedures.is_empty() {
263 info!(
264 "Generating trigger embeddings for {} procedures",
265 procedures.len()
266 );
267 }
268 let mut did_work = !procedures.is_empty();
269 for (id, trigger) in procedures {
270 let trigger = trigger.trim();
271 if trigger.is_empty() {
272 continue;
273 }
274 match embedding_of(embedder, trigger).await {
275 Ok(embedding) => {
276 if let Err(error) = store.save_procedure_embedding(id, trigger, embedding).await {
277 warn!(procedure_id = id, %error, "Failed to project procedure embedding");
278 }
279 }
280 Err(error) => {
281 warn!(procedure_id = id, %error, "Failed to generate trigger embedding for procedure");
282 }
283 }
284 }
285
286 let solutions = store
287 .error_solutions_missing_embedding(EMBEDDING_BACKFILL_BATCH)
288 .await?;
289 if !solutions.is_empty() {
290 info!(
291 "Generating embeddings for {} error solutions",
292 solutions.len()
293 );
294 }
295 did_work |= !solutions.is_empty();
296 for (id, pattern) in solutions {
297 let pattern = pattern.trim();
298 if pattern.is_empty() {
299 continue;
300 }
301 match embedding_of(embedder, pattern).await {
302 Ok(embedding) => {
303 if let Err(error) = store
304 .save_error_solution_embedding(id, pattern, embedding)
305 .await
306 {
307 warn!(error_solution_id = id, %error, "Failed to project error-solution embedding");
308 }
309 }
310 Err(error) => {
311 warn!(error_solution_id = id, %error, "Failed to generate embedding for error solution");
312 }
313 }
314 }
315 Ok(did_work)
316}
317
318pub(crate) async fn embedding_of(embedder: &dyn Embedder, text: &str) -> Result<Vec<f32>> {
320 embedder
321 .embed(&[text.to_string()])
322 .await?
323 .into_iter()
324 .next()
325 .ok_or_else(|| MemoryError::Embedding("embedder returned no vector".to_string()))
326}
327
328pub fn expertise_level(succeeded: i32, failed: i32) -> (&'static str, f32) {
336 let total = succeeded + failed;
337 if total == 0 {
338 return ("novice", 0.0);
339 }
340
341 let success_rate = succeeded as f32 / total as f32;
342 let volume_factor = (total as f32 / 50.0).min(1.0);
343 let confidence = success_rate * volume_factor;
344
345 let level = match (total, success_rate) {
346 (t, r) if t >= 30 && r >= 0.9 => "expert",
347 (t, r) if t >= 15 && r >= 0.8 => "proficient",
348 (t, r) if t >= 5 && r >= 0.7 => "competent",
349 _ => "novice",
350 };
351
352 (level, confidence)
353}
354
355fn normalize_domain(domain: &str) -> Option<&'static str> {
357 match domain.trim().to_ascii_lowercase().as_str() {
358 "rust" => Some("rust"),
359 "python" => Some("python"),
360 "javascript" | "typescript" | "js" | "ts" => Some("javascript"),
361 "go" | "golang" => Some("go"),
362 "docker" => Some("docker"),
363 "kubernetes" | "k8s" => Some("kubernetes"),
364 "infrastructure" | "devops" => Some("infrastructure"),
365 "web-frontend" | "frontend" => Some("web-frontend"),
366 "web-backend" | "backend" => Some("web-backend"),
367 "databases" | "database" | "db" => Some("databases"),
368 "git" => Some("git"),
369 "system-admin" | "sysadmin" | "shell" => Some("system-admin"),
370 "general" => Some("general"),
371 _ => None,
372 }
373}
374
375pub fn detect_domains(explicit_domains: &[String]) -> Vec<String> {
380 let mut domains = Vec::new();
381 for domain in explicit_domains {
382 if let Some(normalized) = normalize_domain(domain) {
383 let normalized = normalized.to_string();
384 if !domains.contains(&normalized) {
385 domains.push(normalized);
386 }
387 }
388 }
389
390 if domains.is_empty() {
391 domains.push("general".to_string());
392 }
393 domains
394}
395
396pub fn generalize_procedure(actions: &[String]) -> Vec<String> {
399 actions
400 .iter()
401 .map(|action| {
402 let generalized = PATH.replace_all(action, "<path>");
403 URL.replace_all(&generalized, "<url>").into_owned()
404 })
405 .collect()
406}
407
408pub fn extract_trigger_pattern(task_context: &str) -> String {
411 let first_sentence = task_context
412 .split('.')
413 .next()
414 .unwrap_or(task_context)
415 .trim();
416 truncate_bytes(first_sentence, 100).to_string()
417}
418
419pub fn procedure_base_name(steps: &[String]) -> String {
424 let mut tools: Vec<String> = Vec::new();
425 for step in steps {
426 let tool: String = step
427 .split(['(', ':'])
428 .next()
429 .unwrap_or_default()
430 .trim()
431 .chars()
432 .filter(|c| c.is_ascii_alphanumeric() || *c == '_')
433 .collect::<String>()
434 .to_ascii_lowercase();
435 if !tool.is_empty() && !tools.contains(&tool) {
436 tools.push(tool);
437 }
438 if tools.len() == 3 {
439 break;
440 }
441 }
442 if tools.is_empty() {
443 "procedure".to_string()
444 } else {
445 tools.join("-")
446 }
447}
448
449pub fn procedure_keyed_name(base_name: &str, steps: &[String]) -> String {
453 use sha2::Digest;
454 let mut hasher = sha2::Sha256::new();
455 for step in steps {
456 hasher.update(step.to_lowercase().as_bytes());
457 hasher.update(b"\n");
458 }
459 let suffix: String = hasher
460 .finalize()
461 .iter()
462 .take(4)
463 .map(|byte| format!("{byte:02x}"))
464 .collect();
465 format!("{base_name}-{suffix}")
466}
467
468pub fn new_procedure(
470 name: String,
471 trigger_pattern: String,
472 steps: Vec<String>,
473 success: bool,
474) -> Procedure {
475 let now = Utc::now();
476 Procedure {
477 id: 0,
478 name,
479 trigger_pattern,
480 steps,
481 success_count: i32::from(success),
482 failure_count: i32::from(!success),
483 avg_duration_secs: None,
484 last_used_at: Some(now),
485 created_at: now,
486 updated_at: now,
487 }
488}
489
490pub fn error_pattern(error: &str) -> String {
493 let pattern = LINE_COLUMN.replace_all(error.trim(), ":<line>");
494 let pattern = PATH.replace_all(&pattern, "<path>");
495 truncate_bytes(&pattern, 200).to_string()
496}
497
498pub fn summarize_solution(actions: &[String]) -> String {
500 if actions.is_empty() {
501 return "No specific actions recorded".to_string();
502 }
503 let tools: Vec<&str> = actions
504 .iter()
505 .filter_map(|action| action.split('(').next())
506 .collect::<std::collections::HashSet<_>>()
507 .into_iter()
508 .collect();
509 format!("Used {} tool(s): {}", tools.len(), tools.join(", "))
510}
511
512pub fn new_error_solution(
515 error_pattern: String,
516 domain: Option<String>,
517 solution_summary: String,
518 solution_steps: Option<Vec<String>>,
519) -> ErrorSolution {
520 let now = Utc::now();
521 ErrorSolution {
522 id: 0,
523 error_pattern,
524 domain,
525 solution_summary,
526 solution_steps,
527 success_count: 1,
528 failure_count: 0,
529 last_used_at: Some(now),
530 created_at: now,
531 }
532}
533
534static PATH: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"/[\w/.-]+").unwrap());
535static URL: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"https?://[^\s)]+").unwrap());
536static LINE_COLUMN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r":\d+:\d+").unwrap());
537
538fn truncate_bytes(text: &str, max: usize) -> &str {
540 if text.len() <= max {
541 return text;
542 }
543 let mut end = max;
544 while !text.is_char_boundary(end) {
545 end -= 1;
546 }
547 &text[..end]
548}
549
550pub fn verbosity_from_messages(messages: &[&str]) -> Option<&'static str> {
554 if messages.is_empty() {
555 return None;
556 }
557 let average = messages.iter().map(|m| m.len() as f32).sum::<f32>() / messages.len() as f32;
558 Some(if average > 200.0 {
559 "detailed"
560 } else if average > 50.0 {
561 "medium"
562 } else {
563 "brief"
564 })
565}
566
567pub async fn update_communication_profile<S>(
571 store: &S,
572 owner_messages: &[&str],
573) -> Result<Option<UserProfile>>
574where
575 S: LearningStore + ?Sized,
576{
577 let Some(verbosity) = verbosity_from_messages(owner_messages) else {
578 return Ok(None);
579 };
580 let Some(mut profile) = store.get_user_profile().await? else {
581 return Ok(None);
582 };
583 profile.verbosity_preference = verbosity.to_string();
584 profile.updated_at = Utc::now();
585 store.update_user_profile(&profile).await?;
586 Ok(Some(profile))
587}
588
589pub fn tool_sequence_patterns(tools: &[String]) -> Vec<(String, String, i32, f32)> {
593 if tools.len() < 3 {
594 return Vec::new();
595 }
596 let mut counts: std::collections::HashMap<(&str, &str), i32> = std::collections::HashMap::new();
597 for pair in tools.windows(2) {
598 *counts
599 .entry((pair[0].as_str(), pair[1].as_str()))
600 .or_insert(0) += 1;
601 }
602 let mut patterns: Vec<(String, String, i32, f32)> = counts
603 .into_iter()
604 .filter(|(_, count)| *count >= 3)
605 .map(|((a, b), count)| {
606 let confidence = (count as f32 / tools.len() as f32).min(0.9);
607 (a.to_string(), b.to_string(), count, confidence)
608 })
609 .collect();
610 patterns.sort_by(|x, y| {
611 y.2.cmp(&x.2)
612 .then_with(|| x.0.cmp(&y.0))
613 .then_with(|| x.1.cmp(&y.1))
614 });
615 patterns
616}
617
618pub async fn record_tool_sequence_patterns<S>(
620 store: &S,
621 tools: &[String],
622) -> Result<Vec<BehaviorPattern>>
623where
624 S: LearningStore + ?Sized,
625{
626 let now = Utc::now();
627 let mut recorded = Vec::new();
628 for (tool_a, tool_b, count, confidence) in tool_sequence_patterns(tools) {
629 let description = format!("After {tool_a} often use {tool_b}");
630 store
631 .record_behavior_pattern(
632 "sequence",
633 &description,
634 Some(&tool_a),
635 Some(&tool_b),
636 confidence,
637 count,
638 )
639 .await?;
640 recorded.push(BehaviorPattern {
641 id: 0,
642 pattern_type: "sequence".to_string(),
643 description,
644 trigger_context: Some(tool_a),
645 action: Some(tool_b),
646 confidence,
647 occurrence_count: count,
648 last_seen_at: Some(now),
649 created_at: now,
650 });
651 }
652 Ok(recorded)
653}
654
655#[cfg(test)]
656mod tests {
657
658 #[test]
659 fn verbosity_reads_message_length_only() {
660 assert_eq!(verbosity_from_messages(&[]), None);
661 assert_eq!(verbosity_from_messages(&["ok", "thanks"]), Some("brief"));
662 let long = "x".repeat(300);
663 assert_eq!(verbosity_from_messages(&[long.as_str()]), Some("detailed"));
664 }
665
666 #[test]
667 fn habits_are_pairs_seen_three_times() {
668 let calls: Vec<String> = ["read", "edit", "read", "edit", "read", "edit", "test"]
669 .into_iter()
670 .map(String::from)
671 .collect();
672 let patterns = tool_sequence_patterns(&calls);
673 assert_eq!(patterns.len(), 1);
674 assert_eq!(
675 (
676 patterns[0].0.as_str(),
677 patterns[0].1.as_str(),
678 patterns[0].2
679 ),
680 ("read", "edit", 3)
681 );
682 assert!(tool_sequence_patterns(&calls[..2]).is_empty());
683 }
684
685 #[test]
686 fn error_patterns_drop_locations() {
687 let pattern = error_pattern(
688 "error[E0382]: borrow of moved value at /home/user/project/src/main.rs:42:10",
689 );
690 assert!(
691 pattern.contains("E0382") && pattern.contains("<path>") && pattern.contains("<line>")
692 );
693 assert!(error_pattern(&"é".repeat(300)).len() <= 200);
694 }
695
696 #[test]
697 fn procedure_names_come_from_the_tools_used() {
698 let steps = vec![
699 "terminal(cargo build)".to_string(),
700 "edit_file(src/main.rs)".to_string(),
701 "terminal(cargo test)".to_string(),
702 ];
703 assert_eq!(procedure_base_name(&steps), "terminal-edit_file");
704 assert_eq!(
705 procedure_base_name(&["terminal: cat <path>".to_string()]),
706 "terminal"
707 );
708 assert_eq!(procedure_base_name(&[]), "procedure");
709 }
710
711 #[test]
712 fn procedures_generalize_and_get_stable_names() {
713 let actions = vec![
714 "terminal(cargo)".to_string(),
715 "web_fetch(/home/user/file.rs)".to_string(),
716 ];
717 assert!(generalize_procedure(&actions)[1].contains("<path>"));
718 let a = procedure_keyed_name("deploy", &actions);
719 assert_eq!(a, procedure_keyed_name("deploy", &actions));
720 assert!(a.starts_with("deploy-"));
721 let failed = new_procedure("n".into(), "t".into(), vec!["cargo test".into()], false);
722 assert_eq!((failed.success_count, failed.failure_count), (0, 1));
723 assert_eq!(
724 extract_trigger_pattern("Run the tests. Then deploy."),
725 "Run the tests"
726 );
727 }
728
729 use super::*;
730
731 #[test]
732 fn test_novice_level() {
733 let (level, _) = expertise_level(0, 0);
734 assert_eq!(level, "novice");
735
736 let (level, _) = expertise_level(2, 2);
737 assert_eq!(level, "novice");
738 }
739
740 #[test]
741 fn test_competent_level() {
742 let (level, _) = expertise_level(7, 3); assert_eq!(level, "competent");
744 }
745
746 #[test]
747 fn test_proficient_level() {
748 let (level, _) = expertise_level(16, 4); assert_eq!(level, "proficient");
750 }
751
752 #[test]
753 fn test_expert_level() {
754 let (level, _) = expertise_level(45, 5); assert_eq!(level, "expert");
756 }
757
758 #[test]
759 fn test_detect_domains() {
760 let domains = detect_domains(&["Rust".to_string(), "typescript".to_string()]);
761 assert!(domains.contains(&"rust".to_string()));
762 assert!(domains.contains(&"javascript".to_string()));
763
764 let domains = detect_domains(&["kubernetes".to_string(), "docker".to_string()]);
765 assert!(domains.contains(&"docker".to_string()));
766 assert!(domains.contains(&"kubernetes".to_string()));
767 }
768
769 #[test]
770 fn test_detect_domains_defaults_general_when_no_explicit_hints() {
771 let domains = detect_domains(&[]);
772 assert_eq!(domains, vec!["general".to_string()]);
773 }
774}