diff --git a/src/mind/mod.rs b/src/mind/mod.rs index 9bf9677..e40b1fd 100644 --- a/src/mind/mod.rs +++ b/src/mind/mod.rs @@ -56,9 +56,9 @@ fn load_memory_scores(section: &mut ContextSection, path: &std::path::Path) { } } -/// Save all memory scores to disk. -fn save_memory_scores(section: &ContextSection, path: &std::path::Path) { - let scores: std::collections::BTreeMap = section.entries().iter() +/// Collect scored memory keys from conversation entries. +fn collect_memory_scores(section: &ContextSection) -> std::collections::BTreeMap { + section.entries().iter() .filter_map(|ce| { if let ConversationEntry::Memory { key, score: Some(s), .. } = &ce.entry { Some((key.clone(), *s)) @@ -66,8 +66,12 @@ fn save_memory_scores(section: &ContextSection, path: &std::path::Path) { None } }) - .collect(); - if let Ok(json) = serde_json::to_string_pretty(&scores) { + .collect() +} + +/// Save memory scores to disk. +fn save_memory_scores(scores: &std::collections::BTreeMap, path: &std::path::Path) { + if let Ok(json) = serde_json::to_string_pretty(scores) { let _ = std::fs::write(path, json); dbglog!("[scoring] saved {} scores to {}", scores.len(), path.display()); } @@ -402,16 +406,21 @@ impl Mind { let agent = agent.clone(); let path = scores_path.clone(); async move { - let mut ag = agent.lock().await; - for i in 0..ag.context.conversation.len() { - if let ConversationEntry::Memory { key: k, .. } = &ag.context.conversation.entries()[i].entry { - if *k == key { - ag.context.conversation.set_score(i, Some(score)); + let scores_snapshot = { + let mut ag = agent.lock().await; + for i in 0..ag.context.conversation.len() { + if let ConversationEntry::Memory { key: k, .. } = &ag.context.conversation.entries()[i].entry { + if *k == key { + ag.context.conversation.set_score(i, Some(score)); + } } } - } - save_memory_scores(&ag.context.conversation, &path); - ag.changed.notify_one(); + ag.changed.notify_one(); + // Snapshot scores while we have the lock + collect_memory_scores(&ag.context.conversation) + }; + // Write to disk after releasing the lock + save_memory_scores(&scores_snapshot, &path); } }, ).await;