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 async fn update_procedure_outcome(
168 &self,
169 _procedure_id: i64,
170 _success: bool,
171 _duration: Option<f32>,
172 ) -> Result<()> {
173 Ok(())
174 }
175
176 async fn insert_error_solution(&self, _solution: &ErrorSolution) -> Result<i64> {
178 Ok(0)
179 }
180
181 async fn update_error_solution_outcome(&self, _solution_id: i64, _success: bool) -> Result<()> {
183 Ok(())
184 }
185
186 async fn record_procedure_observation(&self, procedure: &Procedure) -> Result<()> {
191 self.upsert_procedure(procedure).await.map(|_| ())
192 }
193
194 async fn record_error_solution_observation(&self, solution: &ErrorSolution) -> Result<()> {
197 self.insert_error_solution(solution).await.map(|_| ())
198 }
199
200 async fn record_task_outcome(&self, domain: &str, success: bool) -> Result<()> {
204 self.increment_expertise(domain, success, None).await
205 }
206
207 async fn procedure_trigger_embeddings(&self) -> Result<Vec<Vec<f32>>> {
209 Ok(vec![])
210 }
211
212 async fn set_procedure_trigger_embedding(&self, _name: &str, _embedding: &[f32]) -> Result<()> {
214 Ok(())
215 }
216
217 async fn procedures_missing_embedding(&self, _limit: usize) -> Result<Vec<(i64, String)>> {
219 Ok(vec![])
220 }
221
222 async fn save_procedure_embedding(
224 &self,
225 _id: i64,
226 _trigger: &str,
227 _embedding: Vec<f32>,
228 ) -> Result<()> {
229 Ok(())
230 }
231
232 async fn error_solutions_missing_embedding(&self, _limit: usize) -> Result<Vec<(i64, String)>> {
234 Ok(vec![])
235 }
236
237 async fn save_error_solution_embedding(
239 &self,
240 _id: i64,
241 _pattern: &str,
242 _embedding: Vec<f32>,
243 ) -> Result<()> {
244 Ok(())
245 }
246}
247
248const EMBEDDING_BACKFILL_BATCH: usize = 10;
250
251pub async fn backfill_learning_embeddings<S>(store: &S, embedder: &dyn Embedder) -> Result<bool>
254where
255 S: LearningStore + ?Sized,
256{
257 let procedures = store
258 .procedures_missing_embedding(EMBEDDING_BACKFILL_BATCH)
259 .await?;
260 if !procedures.is_empty() {
261 info!(
262 "Generating trigger embeddings for {} procedures",
263 procedures.len()
264 );
265 }
266 let mut did_work = !procedures.is_empty();
267 for (id, trigger) in procedures {
268 let trigger = trigger.trim();
269 if trigger.is_empty() {
270 continue;
271 }
272 match embedding_of(embedder, trigger).await {
273 Ok(embedding) => {
274 if let Err(error) = store.save_procedure_embedding(id, trigger, embedding).await {
275 warn!(procedure_id = id, %error, "Failed to project procedure embedding");
276 }
277 }
278 Err(error) => {
279 warn!(procedure_id = id, %error, "Failed to generate trigger embedding for procedure");
280 }
281 }
282 }
283
284 let solutions = store
285 .error_solutions_missing_embedding(EMBEDDING_BACKFILL_BATCH)
286 .await?;
287 if !solutions.is_empty() {
288 info!(
289 "Generating embeddings for {} error solutions",
290 solutions.len()
291 );
292 }
293 did_work |= !solutions.is_empty();
294 for (id, pattern) in solutions {
295 let pattern = pattern.trim();
296 if pattern.is_empty() {
297 continue;
298 }
299 match embedding_of(embedder, pattern).await {
300 Ok(embedding) => {
301 if let Err(error) = store
302 .save_error_solution_embedding(id, pattern, embedding)
303 .await
304 {
305 warn!(error_solution_id = id, %error, "Failed to project error-solution embedding");
306 }
307 }
308 Err(error) => {
309 warn!(error_solution_id = id, %error, "Failed to generate embedding for error solution");
310 }
311 }
312 }
313 Ok(did_work)
314}
315
316pub(crate) async fn embedding_of(embedder: &dyn Embedder, text: &str) -> Result<Vec<f32>> {
318 embedder
319 .embed(&[text.to_string()])
320 .await?
321 .into_iter()
322 .next()
323 .ok_or_else(|| MemoryError::Embedding("embedder returned no vector".to_string()))
324}
325
326pub fn expertise_level(succeeded: i32, failed: i32) -> (&'static str, f32) {
334 let total = succeeded + failed;
335 if total == 0 {
336 return ("novice", 0.0);
337 }
338
339 let success_rate = succeeded as f32 / total as f32;
340 let volume_factor = (total as f32 / 50.0).min(1.0);
341 let confidence = success_rate * volume_factor;
342
343 let level = match (total, success_rate) {
344 (t, r) if t >= 30 && r >= 0.9 => "expert",
345 (t, r) if t >= 15 && r >= 0.8 => "proficient",
346 (t, r) if t >= 5 && r >= 0.7 => "competent",
347 _ => "novice",
348 };
349
350 (level, confidence)
351}
352
353fn normalize_domain(domain: &str) -> Option<&'static str> {
355 match domain.trim().to_ascii_lowercase().as_str() {
356 "rust" => Some("rust"),
357 "python" => Some("python"),
358 "javascript" | "typescript" | "js" | "ts" => Some("javascript"),
359 "go" | "golang" => Some("go"),
360 "docker" => Some("docker"),
361 "kubernetes" | "k8s" => Some("kubernetes"),
362 "infrastructure" | "devops" => Some("infrastructure"),
363 "web-frontend" | "frontend" => Some("web-frontend"),
364 "web-backend" | "backend" => Some("web-backend"),
365 "databases" | "database" | "db" => Some("databases"),
366 "git" => Some("git"),
367 "system-admin" | "sysadmin" | "shell" => Some("system-admin"),
368 "general" => Some("general"),
369 _ => None,
370 }
371}
372
373pub fn detect_domains(explicit_domains: &[String]) -> Vec<String> {
378 let mut domains = Vec::new();
379 for domain in explicit_domains {
380 if let Some(normalized) = normalize_domain(domain) {
381 let normalized = normalized.to_string();
382 if !domains.contains(&normalized) {
383 domains.push(normalized);
384 }
385 }
386 }
387
388 if domains.is_empty() {
389 domains.push("general".to_string());
390 }
391 domains
392}
393
394pub fn generalize_procedure(actions: &[String]) -> Vec<String> {
397 actions
398 .iter()
399 .map(|action| {
400 let generalized = PATH.replace_all(action, "<path>");
401 URL.replace_all(&generalized, "<url>").into_owned()
402 })
403 .collect()
404}
405
406pub fn extract_trigger_pattern(task_context: &str) -> String {
409 let first_sentence = task_context
410 .split('.')
411 .next()
412 .unwrap_or(task_context)
413 .trim();
414 truncate_bytes(first_sentence, 100).to_string()
415}
416
417pub fn procedure_base_name(steps: &[String]) -> String {
422 let mut tools: Vec<String> = Vec::new();
423 for step in steps {
424 let tool: String = step
425 .split(['(', ':'])
426 .next()
427 .unwrap_or_default()
428 .trim()
429 .chars()
430 .filter(|c| c.is_ascii_alphanumeric() || *c == '_')
431 .collect::<String>()
432 .to_ascii_lowercase();
433 if !tool.is_empty() && !tools.contains(&tool) {
434 tools.push(tool);
435 }
436 if tools.len() == 3 {
437 break;
438 }
439 }
440 if tools.is_empty() {
441 "procedure".to_string()
442 } else {
443 tools.join("-")
444 }
445}
446
447pub fn procedure_keyed_name(base_name: &str, steps: &[String]) -> String {
451 use sha2::Digest;
452 let mut hasher = sha2::Sha256::new();
453 for step in steps {
454 hasher.update(step.to_lowercase().as_bytes());
455 hasher.update(b"\n");
456 }
457 let suffix: String = hasher
458 .finalize()
459 .iter()
460 .take(4)
461 .map(|byte| format!("{byte:02x}"))
462 .collect();
463 format!("{base_name}-{suffix}")
464}
465
466pub fn new_procedure(
468 name: String,
469 trigger_pattern: String,
470 steps: Vec<String>,
471 success: bool,
472) -> Procedure {
473 let now = Utc::now();
474 Procedure {
475 id: 0,
476 name,
477 trigger_pattern,
478 steps,
479 success_count: i32::from(success),
480 failure_count: i32::from(!success),
481 avg_duration_secs: None,
482 last_used_at: Some(now),
483 created_at: now,
484 updated_at: now,
485 }
486}
487
488pub fn error_pattern(error: &str) -> String {
491 let pattern = LINE_COLUMN.replace_all(error.trim(), ":<line>");
492 let pattern = PATH.replace_all(&pattern, "<path>");
493 truncate_bytes(&pattern, 200).to_string()
494}
495
496pub fn summarize_solution(actions: &[String]) -> String {
498 if actions.is_empty() {
499 return "No specific actions recorded".to_string();
500 }
501 let tools: Vec<&str> = actions
502 .iter()
503 .filter_map(|action| action.split('(').next())
504 .collect::<std::collections::HashSet<_>>()
505 .into_iter()
506 .collect();
507 format!("Used {} tool(s): {}", tools.len(), tools.join(", "))
508}
509
510pub fn new_error_solution(
513 error_pattern: String,
514 domain: Option<String>,
515 solution_summary: String,
516 solution_steps: Option<Vec<String>>,
517) -> ErrorSolution {
518 let now = Utc::now();
519 ErrorSolution {
520 id: 0,
521 error_pattern,
522 domain,
523 solution_summary,
524 solution_steps,
525 success_count: 1,
526 failure_count: 0,
527 last_used_at: Some(now),
528 created_at: now,
529 }
530}
531
532static PATH: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"/[\w/.-]+").unwrap());
533static URL: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"https?://[^\s)]+").unwrap());
534static LINE_COLUMN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r":\d+:\d+").unwrap());
535
536fn truncate_bytes(text: &str, max: usize) -> &str {
538 if text.len() <= max {
539 return text;
540 }
541 let end = text.floor_char_boundary(max);
542 &text[..end]
543}
544
545pub fn verbosity_from_messages(messages: &[&str]) -> Option<&'static str> {
549 if messages.is_empty() {
550 return None;
551 }
552 let average = messages.iter().map(|m| m.len() as f32).sum::<f32>() / messages.len() as f32;
553 Some(if average > 200.0 {
554 "detailed"
555 } else if average > 50.0 {
556 "medium"
557 } else {
558 "brief"
559 })
560}
561
562pub async fn update_communication_profile<S>(
566 store: &S,
567 owner_messages: &[&str],
568) -> Result<Option<UserProfile>>
569where
570 S: LearningStore + ?Sized,
571{
572 let Some(verbosity) = verbosity_from_messages(owner_messages) else {
573 return Ok(None);
574 };
575 let Some(mut profile) = store.get_user_profile().await? else {
576 return Ok(None);
577 };
578 profile.verbosity_preference = verbosity.to_string();
579 profile.updated_at = Utc::now();
580 store.update_user_profile(&profile).await?;
581 Ok(Some(profile))
582}
583
584pub fn tool_sequence_patterns(tools: &[String]) -> Vec<(String, String, i32, f32)> {
588 if tools.len() < 3 {
589 return Vec::new();
590 }
591 let mut counts: std::collections::HashMap<(&str, &str), i32> = std::collections::HashMap::new();
592 for pair in tools.windows(2) {
593 *counts
594 .entry((pair[0].as_str(), pair[1].as_str()))
595 .or_insert(0) += 1;
596 }
597 let mut patterns: Vec<(String, String, i32, f32)> = counts
598 .into_iter()
599 .filter(|(_, count)| *count >= 3)
600 .map(|((a, b), count)| {
601 let confidence = (count as f32 / tools.len() as f32).min(0.9);
602 (a.to_string(), b.to_string(), count, confidence)
603 })
604 .collect();
605 patterns.sort_by(|x, y| {
606 y.2.cmp(&x.2)
607 .then_with(|| x.0.cmp(&y.0))
608 .then_with(|| x.1.cmp(&y.1))
609 });
610 patterns
611}
612
613pub async fn record_tool_sequence_patterns<S>(
615 store: &S,
616 tools: &[String],
617) -> Result<Vec<BehaviorPattern>>
618where
619 S: LearningStore + ?Sized,
620{
621 let now = Utc::now();
622 let mut recorded = Vec::new();
623 for (tool_a, tool_b, count, confidence) in tool_sequence_patterns(tools) {
624 let description = format!("After {tool_a} often use {tool_b}");
625 store
626 .record_behavior_pattern(
627 "sequence",
628 &description,
629 Some(&tool_a),
630 Some(&tool_b),
631 confidence,
632 count,
633 )
634 .await?;
635 recorded.push(BehaviorPattern {
636 id: 0,
637 pattern_type: "sequence".to_string(),
638 description,
639 trigger_context: Some(tool_a),
640 action: Some(tool_b),
641 confidence,
642 occurrence_count: count,
643 last_seen_at: Some(now),
644 created_at: now,
645 });
646 }
647 Ok(recorded)
648}
649
650#[cfg(test)]
651mod tests {
652
653 #[test]
654 fn verbosity_reads_message_length_only() {
655 assert_eq!(verbosity_from_messages(&[]), None);
656 assert_eq!(verbosity_from_messages(&["ok", "thanks"]), Some("brief"));
657 let long = "x".repeat(300);
658 assert_eq!(verbosity_from_messages(&[long.as_str()]), Some("detailed"));
659 }
660
661 #[test]
662 fn habits_are_pairs_seen_three_times() {
663 let calls: Vec<String> = ["read", "edit", "read", "edit", "read", "edit", "test"]
664 .into_iter()
665 .map(String::from)
666 .collect();
667 let patterns = tool_sequence_patterns(&calls);
668 assert_eq!(patterns.len(), 1);
669 assert_eq!(
670 (
671 patterns[0].0.as_str(),
672 patterns[0].1.as_str(),
673 patterns[0].2
674 ),
675 ("read", "edit", 3)
676 );
677 assert!(tool_sequence_patterns(&calls[..2]).is_empty());
678 }
679
680 #[test]
681 fn error_patterns_drop_locations() {
682 let pattern = error_pattern(
683 "error[E0382]: borrow of moved value at /home/user/project/src/main.rs:42:10",
684 );
685 assert!(
686 pattern.contains("E0382") && pattern.contains("<path>") && pattern.contains("<line>")
687 );
688 assert!(error_pattern(&"é".repeat(300)).len() <= 200);
689 }
690
691 #[test]
692 fn procedure_names_come_from_the_tools_used() {
693 let steps = vec![
694 "terminal(cargo build)".to_string(),
695 "edit_file(src/main.rs)".to_string(),
696 "terminal(cargo test)".to_string(),
697 ];
698 assert_eq!(procedure_base_name(&steps), "terminal-edit_file");
699 assert_eq!(
700 procedure_base_name(&["terminal: cat <path>".to_string()]),
701 "terminal"
702 );
703 assert_eq!(procedure_base_name(&[]), "procedure");
704 }
705
706 #[test]
707 fn procedures_generalize_and_get_stable_names() {
708 let actions = vec![
709 "terminal(cargo)".to_string(),
710 "web_fetch(/home/user/file.rs)".to_string(),
711 ];
712 assert!(generalize_procedure(&actions)[1].contains("<path>"));
713 let a = procedure_keyed_name("deploy", &actions);
714 assert_eq!(a, procedure_keyed_name("deploy", &actions));
715 assert!(a.starts_with("deploy-"));
716 let failed = new_procedure("n".into(), "t".into(), vec!["cargo test".into()], false);
717 assert_eq!((failed.success_count, failed.failure_count), (0, 1));
718 assert_eq!(
719 extract_trigger_pattern("Run the tests. Then deploy."),
720 "Run the tests"
721 );
722 }
723
724 use super::*;
725
726 #[test]
727 fn test_novice_level() {
728 let (level, _) = expertise_level(0, 0);
729 assert_eq!(level, "novice");
730
731 let (level, _) = expertise_level(2, 2);
732 assert_eq!(level, "novice");
733 }
734
735 #[test]
736 fn test_competent_level() {
737 let (level, _) = expertise_level(7, 3); assert_eq!(level, "competent");
739 }
740
741 #[test]
742 fn test_proficient_level() {
743 let (level, _) = expertise_level(16, 4); assert_eq!(level, "proficient");
745 }
746
747 #[test]
748 fn test_expert_level() {
749 let (level, _) = expertise_level(45, 5); assert_eq!(level, "expert");
751 }
752
753 #[test]
754 fn test_detect_domains() {
755 let domains = detect_domains(&["Rust".to_string(), "typescript".to_string()]);
756 assert!(domains.contains(&"rust".to_string()));
757 assert!(domains.contains(&"javascript".to_string()));
758
759 let domains = detect_domains(&["kubernetes".to_string(), "docker".to_string()]);
760 assert!(domains.contains(&"docker".to_string()));
761 assert!(domains.contains(&"kubernetes".to_string()));
762 }
763
764 #[test]
765 fn test_detect_domains_defaults_general_when_no_explicit_hints() {
766 let domains = detect_domains(&[]);
767 assert_eq!(domains, vec!["general".to_string()]);
768 }
769}