Skip to main content

lean_ctx/core/memory_scheduler/
decay.rs

1//! Project-scoped knowledge decay and reinjection scheduling.
2//!
3//! Persists per-fact [`MemoryState`] values and uses FSRS retrievability to
4//! decide when stale facts should re-enter agent context.
5
6use std::collections::HashMap;
7use std::path::PathBuf;
8
9use chrono::Utc;
10use serde::{Deserialize, Serialize};
11
12use crate::core::data_dir::lean_ctx_data_dir;
13use crate::core::memory_scheduler::fsrs::{
14    MemoryState, initial_state, retrievability, update_stability,
15};
16
17/// Manages FSRS memory states for all knowledge facts in a project.
18#[derive(Debug, Clone, Serialize, Deserialize, Default)]
19pub struct KnowledgeDecayModel {
20    /// Memory states indexed by stable knowledge-fact key.
21    pub states: HashMap<String, MemoryState>,
22}
23
24impl KnowledgeDecayModel {
25    /// Load a project's memory schedule, returning an empty model on failure.
26    pub fn load(project_hash: &str) -> Self {
27        let Some(path) = Self::path(project_hash) else {
28            return Self::default();
29        };
30        std::fs::read_to_string(path)
31            .ok()
32            .and_then(|content| serde_json::from_str(&content).ok())
33            .unwrap_or_default()
34    }
35
36    /// Save a project's memory schedule to disk when its data directory is available.
37    pub fn save(&self, project_hash: &str) {
38        let Some(path) = Self::path(project_hash) else {
39            return;
40        };
41        let Some(parent) = path.parent() else {
42            return;
43        };
44        if std::fs::create_dir_all(parent).is_err() {
45            return;
46        }
47        let Ok(json) = serde_json::to_string_pretty(self) else {
48            return;
49        };
50        let temporary_path = path.with_extension("tmp");
51        if std::fs::write(&temporary_path, json).is_ok() {
52            let _ = std::fs::rename(temporary_path, path);
53        }
54    }
55
56    /// Check whether a fact's retrievability is below `threshold`.
57    pub fn should_reinject(&self, key: &str, threshold: f64) -> bool {
58        let threshold = threshold.clamp(0.0, 1.0);
59        match self.states.get(key) {
60            Some(state) => retrievability(state, Utc::now()) < threshold,
61            None => true,
62        }
63    }
64
65    /// Record a fact review or successful use with the supplied FSRS rating.
66    pub fn record_use(&mut self, key: &str, rating: u8) {
67        if let Some(state) = self.states.get_mut(key) {
68            update_stability(state, rating);
69        } else {
70            self.states
71                .insert(key.to_string(), initial_state(key.to_string(), rating));
72        }
73    }
74
75    /// Return fact keys whose retrievability is below `threshold`.
76    pub fn stale_facts(&self, threshold: f64) -> Vec<String> {
77        let now = Utc::now();
78        let mut stale = self
79            .states
80            .iter()
81            .filter(|(_, state)| retrievability(state, now) < threshold)
82            .map(|(key, _)| key.clone())
83            .collect::<Vec<_>>();
84        stale.sort();
85        stale
86    }
87
88    /// Return all facts from lowest to highest retrievability.
89    pub fn urgency_ranked(&self) -> Vec<(&str, f64)> {
90        let now = Utc::now();
91        let mut ranked = self
92            .states
93            .iter()
94            .map(|(key, state)| (key.as_str(), retrievability(state, now)))
95            .collect::<Vec<_>>();
96        ranked.sort_by(|left, right| left.1.total_cmp(&right.1).then_with(|| left.0.cmp(right.0)));
97        ranked
98    }
99
100    /// Resolve the persisted memory-schedule path for a project.
101    fn path(project_hash: &str) -> Option<PathBuf> {
102        lean_ctx_data_dir().ok().map(|data_dir| {
103            data_dir
104                .join("knowledge")
105                .join(project_hash)
106                .join("memory_schedule.json")
107        })
108    }
109}
110
111#[cfg(test)]
112pub mod tests {
113    use chrono::{Duration, Utc};
114
115    use crate::core::memory_scheduler::decay::KnowledgeDecayModel;
116    use crate::core::memory_scheduler::fsrs::initial_state;
117
118    #[test]
119    fn should_reinject_true_for_unknown_fact() {
120        let model = KnowledgeDecayModel::default();
121
122        assert!(model.should_reinject("unknown", 0.9));
123    }
124
125    #[test]
126    fn should_reinject_false_immediately_after_use() {
127        let mut model = KnowledgeDecayModel::default();
128        model.record_use("recent", 3);
129
130        assert!(!model.should_reinject("recent", 0.9));
131    }
132
133    #[test]
134    fn stale_facts_returns_old_entries() {
135        let mut model = KnowledgeDecayModel::default();
136        let mut old = initial_state("old".to_string(), 1);
137        old.last_review = Utc::now() - Duration::days(30);
138        model.states.insert("old".to_string(), old);
139        model.record_use("recent", 3);
140
141        assert_eq!(model.stale_facts(0.9), vec!["old".to_string()]);
142    }
143}