Skip to main content

lean_ctx/core/knowledge/
persist.rs

1use chrono::Utc;
2use std::collections::{HashMap, HashSet};
3use std::path::{Path, PathBuf};
4use std::sync::{Arc, Mutex, OnceLock};
5
6use super::ranking::hash_project_root;
7use super::types::{ConsolidatedInsight, KnowledgeFact, ProjectKnowledge, ProjectPattern};
8use crate::core::memory_policy::MemoryPolicy;
9
10fn knowledge_dir(project_hash: &str) -> Result<PathBuf, String> {
11    Ok(crate::core::data_dir::lean_ctx_data_dir()?
12        .join("knowledge")
13        .join(project_hash))
14}
15
16/// Per-project-hash mutex registry. Serializes the read-modify-write cycle of
17/// `mutate_locked` so concurrent `remember` calls within a single process (e.g.
18/// parallel MCP tool calls) cannot clobber each other (issue #326). The outer
19/// map lock is held only briefly to clone the inner `Arc`; the inner lock is
20/// held across the load → mutate → save cycle.
21fn knowledge_lock(project_hash: &str) -> Arc<Mutex<()>> {
22    static KNOWLEDGE_LOCKS: OnceLock<Mutex<HashMap<String, Arc<Mutex<()>>>>> = OnceLock::new();
23    let map = KNOWLEDGE_LOCKS.get_or_init(|| Mutex::new(HashMap::new()));
24    let mut guard = map
25        .lock()
26        .unwrap_or_else(std::sync::PoisonError::into_inner);
27    guard
28        .entry(project_hash.to_string())
29        .or_insert_with(|| Arc::new(Mutex::new(())))
30        .clone()
31}
32
33/// Acquires an exclusive, cross-process advisory lock for a project's
34/// knowledge store. The returned file handle holds the lock until it is
35/// dropped; the OS releases it automatically if the process exits (even on
36/// crash), so there are no stale locks. This serializes the read-modify-write
37/// cycle across *separate processes* (parallel CLI invocations, CLI + daemon +
38/// MCP server), complementing the in-process mutex (issue #326).
39fn acquire_file_lock(dir: &Path) -> Option<std::fs::File> {
40    use fs2::FileExt;
41    let lock_path = dir.join(".knowledge.lock");
42    let file = std::fs::OpenOptions::new()
43        .create(true)
44        .truncate(false)
45        .write(true)
46        .open(&lock_path)
47        .ok()?;
48    #[cfg(unix)]
49    {
50        use std::os::unix::fs::PermissionsExt;
51        let _ = std::fs::set_permissions(&lock_path, std::fs::Permissions::from_mode(0o600));
52    }
53    // Blocks until every other process holding the lock releases it. A failure
54    // here (unsupported FS, etc.) degrades to the in-process lock only.
55    file.lock_exclusive().ok()?;
56    Some(file)
57}
58
59/// Atomically writes `json` to `path` by writing to a unique temp file in the
60/// same directory and renaming it into place. `rename` is atomic on every
61/// supported platform (and replaces the target on Windows), so readers and
62/// concurrent writers never observe a half-written file — preventing the
63/// trailing-garbage JSON corruption reported in issue #326.
64fn write_json_atomic(dir: &Path, path: &Path, json: &str) -> Result<(), String> {
65    let unique = format!(
66        "knowledge.json.tmp.{}.{}",
67        std::process::id(),
68        std::time::SystemTime::now()
69            .duration_since(std::time::UNIX_EPOCH)
70            .map_or(0, |d| d.as_nanos())
71    );
72    let tmp = dir.join(unique);
73    std::fs::write(&tmp, json).map_err(|e| e.to_string())?;
74    #[cfg(unix)]
75    {
76        use std::os::unix::fs::PermissionsExt;
77        let _ = std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600));
78    }
79    if let Err(e) = std::fs::rename(&tmp, path) {
80        let _ = std::fs::remove_file(&tmp);
81        return Err(e.to_string());
82    }
83    Ok(())
84}
85
86impl ProjectKnowledge {
87    /// Return the most recent active decision-like facts for session handoff.
88    /// Adds a pre-built fact, coalescing repeated observations into confirmations.
89    pub fn add_fact(&mut self, mut fact: KnowledgeFact) -> bool {
90        let trimmed_cat = fact.category.trim().to_string();
91        fact.category = trimmed_cat;
92        let trimmed_val = fact.value.trim().to_string();
93        fact.value = trimmed_val;
94        if fact.category.is_empty() || fact.value.is_empty() {
95            return false;
96        }
97
98        if let Some(existing) = self
99            .facts
100            .iter_mut()
101            .find(|existing| existing.category == fact.category && existing.value == fact.value)
102        {
103            if fact.last_confirmed > existing.last_confirmed {
104                existing.last_confirmed = fact.last_confirmed;
105            }
106            existing.confidence = existing.confidence.max(fact.confidence);
107            existing.confirmation_count = existing.confirmation_count.saturating_add(1);
108            existing.update_fidelity();
109        } else {
110            fact.update_fidelity();
111            self.facts.push(fact);
112            self.rebuild_index();
113        }
114
115        self.updated_at = Utc::now();
116        true
117    }
118
119    pub fn recent_decisions(&self, limit: usize) -> Vec<KnowledgeFact> {
120        let mut decisions: Vec<KnowledgeFact> = self
121            .facts
122            .iter()
123            .filter(|fact| {
124                let category = fact.category.to_ascii_lowercase();
125                fact.is_current()
126                    && (category.contains("decision")
127                        || category.contains("architecture")
128                        || category.contains("solution"))
129            })
130            .cloned()
131            .collect();
132        decisions.sort_by(|a, b| {
133            b.last_confirmed
134                .cmp(&a.last_confirmed)
135                .then_with(|| b.created_at.cmp(&a.created_at))
136        });
137        decisions.truncate(limit);
138        decisions
139    }
140    /// Keyword-based knowledge search across all facts.
141    /// Serves as the API surface for semantic retrieval; currently falls back
142    /// to substring matching. When the embedding model is loaded, this will
143    /// use HNSW vector search instead.
144    pub fn search_semantic(&self, query: &str, limit: usize) -> Vec<KnowledgeFact> {
145        let query_lower = query.to_lowercase();
146        let terms: Vec<&str> = query_lower.split_whitespace().collect();
147        if terms.is_empty() {
148            return Vec::new();
149        }
150        let mut scored: Vec<(usize, &KnowledgeFact)> = self
151            .facts
152            .iter()
153            .filter(|f| f.valid_until.is_none_or(|t| t > chrono::Utc::now()))
154            .map(|fact| {
155                let haystack = format!(
156                    "{} {} {}",
157                    fact.category.to_lowercase(),
158                    fact.value.to_lowercase(),
159                    fact.key.to_lowercase(),
160                );
161                let score = terms.iter().filter(|t| haystack.contains(*t)).count();
162                (score, fact)
163            })
164            .filter(|(score, _)| *score > 0)
165            .collect();
166        scored.sort_by_key(|a| std::cmp::Reverse(a.0));
167        scored
168            .into_iter()
169            .take(limit)
170            .map(|(_, f)| f.clone())
171            .collect()
172    }
173
174    pub fn list_project_roots() -> Result<Vec<String>, String> {
175        let base = crate::core::data_dir::lean_ctx_data_dir()?.join("knowledge");
176        if !base.exists() {
177            return Ok(Vec::new());
178        }
179
180        let mut roots = Vec::new();
181        let mut seen = HashSet::new();
182        let entries = std::fs::read_dir(&base).map_err(|e| e.to_string())?;
183        for entry in entries.flatten() {
184            let path = entry.path().join("knowledge.json");
185            if !path.is_file() {
186                continue;
187            }
188            let Ok(content) = std::fs::read_to_string(&path) else {
189                continue;
190            };
191            let Ok(knowledge) = serde_json::from_str::<Self>(&content) else {
192                continue;
193            };
194            if seen.insert(knowledge.project_root.clone()) {
195                roots.push(knowledge.project_root);
196            }
197        }
198
199        roots.sort();
200        Ok(roots)
201    }
202
203    pub fn save(&self) -> Result<(), String> {
204        let dir = knowledge_dir(&self.project_hash)?;
205        std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
206        #[cfg(unix)]
207        {
208            use std::os::unix::fs::PermissionsExt;
209            let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
210        }
211
212        let path = dir.join("knowledge.json");
213        let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
214        write_json_atomic(&dir, &path, &json)?;
215        Ok(())
216    }
217
218    /// Runs `f` while holding this project's locks — the in-process per-hash
219    /// mutex *and* the cross-process advisory file lock — without loading or
220    /// saving the knowledge JSON itself. [`mutate_locked`](Self::mutate_locked)
221    /// is built on this, and side-car stores that must stay consistent with the
222    /// facts (today: the embedding index) call it directly so their
223    /// read-modify-write is serialized against parallel
224    /// `remember`/`remove`/`reindex`. That side-car write used to run lock-free,
225    /// so concurrent callers clobbered each other's embeddings and pruned
226    /// just-stored vectors, degrading semantic recall (issue #412, a #326
227    /// follow-up).
228    pub(crate) fn with_project_lock<T>(project_root: &str, f: impl FnOnce() -> T) -> T {
229        let hash = hash_project_root(project_root);
230        let lock = knowledge_lock(&hash);
231        let _guard = lock
232            .lock()
233            .unwrap_or_else(std::sync::PoisonError::into_inner);
234
235        // Cross-process lock: create the dir up front so the lock file has a
236        // home, then block until any other process releases it. Held for the
237        // whole critical section via `_file_lock`'s lifetime.
238        let _file_lock = match knowledge_dir(&hash) {
239            Ok(dir) => {
240                let _ = std::fs::create_dir_all(&dir);
241                acquire_file_lock(&dir)
242            }
243            Err(_) => None,
244        };
245
246        f()
247    }
248
249    /// Runs a read-modify-write cycle under `with_project_lock`, then saves
250    /// atomically. The knowledge is (re)loaded *inside* the lock so
251    /// the closure always operates on the latest on-disk state; this is what
252    /// prevents lost updates when several `remember` calls run in parallel —
253    /// whether as threads in one process (parallel MCP calls) or as separate
254    /// processes (parallel CLI invocations, CLI + daemon + MCP server) — see
255    /// issue #326. Returns the persisted knowledge plus the closure's return
256    /// value so the caller can build a response from the committed state.
257    pub fn mutate_locked<T>(
258        project_root: &str,
259        f: impl FnOnce(&mut Self) -> T,
260    ) -> Result<(Self, T), String> {
261        Self::with_project_lock(project_root, || {
262            let mut knowledge = Self::load_or_create(project_root);
263            let out = f(&mut knowledge);
264            knowledge.save()?;
265            Ok((knowledge, out))
266        })
267    }
268
269    pub fn load(project_root: &str) -> Option<Self> {
270        let hash = hash_project_root(project_root);
271        let dir = knowledge_dir(&hash).ok()?;
272        let path = dir.join("knowledge.json");
273
274        if let Ok(content) = std::fs::read_to_string(&path) {
275            let size = content.len();
276            if size > 1_000_000 {
277                tracing::warn!(
278                    "knowledge.json is large ({:.1} MB) — recall may be slow. \
279                     Consider running ctx_knowledge(action=\"consolidate\") to compact it.",
280                    size as f64 / 1_048_576.0,
281                );
282            }
283            if let Ok(mut k) = serde_json::from_str::<Self>(&content) {
284                k.rebuild_index();
285                return Some(k);
286            }
287        }
288
289        let old_hash = crate::core::project_hash::hash_path_only(project_root);
290        if old_hash != hash {
291            crate::core::project_hash::migrate_if_needed(&old_hash, &hash, project_root);
292            if let Ok(content) = std::fs::read_to_string(&path)
293                && let Ok(mut k) = serde_json::from_str::<Self>(&content)
294            {
295                k.project_hash = hash;
296                k.rebuild_index();
297                let _ = k.save();
298                return Some(k);
299            }
300        }
301
302        // Migrate stores created before path normalization (issue #325): on
303        // Windows the CLI keyed its store by a backslash path, splitting it from
304        // the forward-slash MCP store. Pull any such legacy store into the
305        // canonical (normalized) location so facts converge.
306        for legacy_hash in crate::core::project_hash::legacy_unnormalized_hashes(project_root) {
307            if legacy_hash == hash {
308                continue;
309            }
310            crate::core::project_hash::migrate_if_needed(&legacy_hash, &hash, project_root);
311            if let Ok(content) = std::fs::read_to_string(&path)
312                && let Ok(mut k) = serde_json::from_str::<Self>(&content)
313            {
314                k.project_hash = hash;
315                k.rebuild_index();
316                let _ = k.save();
317                return Some(k);
318            }
319        }
320
321        None
322    }
323
324    pub fn load_or_create(project_root: &str) -> Self {
325        Self::load(project_root).unwrap_or_else(|| Self::new(project_root))
326    }
327
328    /// Migrates legacy knowledge that was accidentally stored under an empty project_root ("")
329    /// into the given `target_root`. Keeps a timestamped backup of the legacy file.
330    pub fn migrate_legacy_empty_root(
331        target_root: &str,
332        policy: &MemoryPolicy,
333    ) -> Result<bool, String> {
334        if target_root.trim().is_empty() {
335            return Ok(false);
336        }
337
338        let Some(legacy) = Self::load("") else {
339            return Ok(false);
340        };
341
342        if !legacy.project_root.trim().is_empty() {
343            return Ok(false);
344        }
345        if legacy.facts.is_empty() && legacy.patterns.is_empty() && legacy.history.is_empty() {
346            return Ok(false);
347        }
348
349        let mut target = Self::load_or_create(target_root);
350
351        fn fact_key(f: &KnowledgeFact) -> String {
352            format!(
353                "{}|{}|{}|{}|{}",
354                f.category, f.key, f.value, f.source_session, f.created_at
355            )
356        }
357        fn pattern_key(p: &ProjectPattern) -> String {
358            format!(
359                "{}|{}|{}|{}",
360                p.pattern_type, p.description, p.source_session, p.created_at
361            )
362        }
363        fn history_key(h: &ConsolidatedInsight) -> String {
364            format!(
365                "{}|{}|{}",
366                h.summary,
367                h.from_sessions.join(","),
368                h.timestamp
369            )
370        }
371
372        let mut seen_facts: std::collections::HashSet<String> =
373            target.facts.iter().map(fact_key).collect();
374        for f in legacy.facts {
375            if seen_facts.insert(fact_key(&f)) {
376                target.facts.push(f);
377            }
378        }
379
380        let mut seen_patterns: std::collections::HashSet<String> =
381            target.patterns.iter().map(pattern_key).collect();
382        for p in legacy.patterns {
383            if seen_patterns.insert(pattern_key(&p)) {
384                target.patterns.push(p);
385            }
386        }
387
388        let mut seen_history: std::collections::HashSet<String> =
389            target.history.iter().map(history_key).collect();
390        for h in legacy.history {
391            if seen_history.insert(history_key(&h)) {
392                target.history.push(h);
393            }
394        }
395
396        target.facts.sort_by(|a, b| {
397            b.created_at
398                .cmp(&a.created_at)
399                .then_with(|| b.confidence.total_cmp(&a.confidence))
400        });
401        if target.facts.len() > policy.knowledge.max_facts {
402            target.facts.truncate(policy.knowledge.max_facts);
403        }
404        target
405            .patterns
406            .sort_by_key(|x| std::cmp::Reverse(x.created_at));
407        if target.patterns.len() > policy.knowledge.max_patterns {
408            target.patterns.truncate(policy.knowledge.max_patterns);
409        }
410        target
411            .history
412            .sort_by_key(|x| std::cmp::Reverse(x.timestamp));
413        if target.history.len() > policy.knowledge.max_history {
414            target.history.truncate(policy.knowledge.max_history);
415        }
416
417        target.updated_at = Utc::now();
418        target.save()?;
419
420        let legacy_hash = crate::core::project_hash::hash_path_only("");
421        let legacy_dir = knowledge_dir(&legacy_hash)?;
422        let legacy_path = legacy_dir.join("knowledge.json");
423        if legacy_path.exists() {
424            let ts = Utc::now().format("%Y%m%d-%H%M%S");
425            let backup = legacy_dir.join(format!("knowledge.legacy-empty-root.{ts}.json"));
426            std::fs::rename(&legacy_path, &backup).map_err(|e| e.to_string())?;
427        }
428
429        Ok(true)
430    }
431}
432
433#[cfg(test)]
434mod tests {
435    use super::*;
436    use fs2::FileExt;
437
438    #[test]
439    fn file_lock_is_exclusive_across_handles() {
440        // flock-style locks are tied to the open file description, so two
441        // independent `open()`s in the same process behave like two separate
442        // processes: while the first holds the exclusive lock, the second must
443        // fail to acquire it. This validates the cross-process guarantee that
444        // protects parallel CLI writes (issue #326).
445        let dir = tempfile::tempdir().unwrap();
446        let held = acquire_file_lock(dir.path()).expect("first lock must succeed");
447
448        let second = std::fs::OpenOptions::new()
449            .create(true)
450            .truncate(false)
451            .write(true)
452            .open(dir.path().join(".knowledge.lock"))
453            .unwrap();
454        assert!(
455            second.try_lock_exclusive().is_err(),
456            "a second handle must not acquire the lock while it is held"
457        );
458
459        drop(held);
460        // `close()` releases the flock synchronously, so the lock IS free here.
461        // Under heavy parallel test load, however, a single non-blocking
462        // `try_lock_exclusive()` can momentarily observe `EWOULDBLOCK` from
463        // scheduling jitter. A short bounded retry removes that flake without
464        // weakening the guarantee: the lock must become acquirable again.
465        let mut reacquired = false;
466        for _ in 0..50 {
467            if second.try_lock_exclusive().is_ok() {
468                reacquired = true;
469                break;
470            }
471            std::thread::sleep(std::time::Duration::from_millis(10));
472        }
473        assert!(
474            reacquired,
475            "lock must be acquirable within 500ms of release"
476        );
477    }
478
479    #[test]
480    fn write_json_atomic_leaves_valid_file_and_no_temp() {
481        let dir = tempfile::tempdir().unwrap();
482        let path = dir.path().join("knowledge.json");
483        write_json_atomic(dir.path(), &path, "{\"ok\":true}").unwrap();
484        assert_eq!(std::fs::read_to_string(&path).unwrap(), "{\"ok\":true}");
485        let leftover = std::fs::read_dir(dir.path())
486            .unwrap()
487            .filter_map(Result::ok)
488            .any(|e| e.file_name().to_string_lossy().contains(".tmp."));
489        assert!(!leftover, "no temp file should remain");
490    }
491
492    #[test]
493    fn load_rebuilds_ephemeral_index_without_changing_json() {
494        let _isolated = crate::core::data_dir::isolated_data_dir();
495        let root = "/tmp/knowledge-index-load";
496        let policy = MemoryPolicy::default();
497        let mut knowledge = ProjectKnowledge::new(root);
498        knowledge.remember(
499            "architecture",
500            "database",
501            "PostgreSQL",
502            "test",
503            0.9,
504            &policy,
505        );
506        knowledge.save().unwrap();
507
508        let loaded = ProjectKnowledge::load(root).expect("saved knowledge should load");
509        assert!(loaded.index.token_positions.contains_key("postgresql"));
510        assert_eq!(loaded.recall("postgresql").len(), 1);
511
512        let json = serde_json::to_string(&loaded).unwrap();
513        assert!(!json.contains("\"index\""));
514    }
515}