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
86/// Marker that identifies a fact as machine-derived rather than curated.
87///
88/// Both automatic producers already carry it: `extract_session_facts` tags the
89/// *category* (`auto:decision`, `auto:pattern`, `auto:blocker`) and
90/// `auto_capture` derives an `auto:`-prefixed *key*. Nothing a person writes
91/// through `ctx_knowledge(action="remember")` does.
92pub(crate) const MACHINE_DERIVED_PREFIX: &str = "auto:";
93
94/// Whether this fact was derived by lean-ctx rather than written by a person.
95pub(crate) fn is_machine_derived(category: &str, key: &str) -> bool {
96    category.trim_start().starts_with(MACHINE_DERIVED_PREFIX)
97        || key.trim_start().starts_with(MACHINE_DERIVED_PREFIX)
98}
99
100/// Whether a machine-derived fact may enter the durable store right now.
101///
102/// #1802: `auto_capture = false` was honoured by exactly one producer
103/// (`auto_capture::capture_finding`) and ignored by the other
104/// (`extract_session_facts`, reached from both the consolidation engine and
105/// the session *save* path) — so a single MCP call re-materialised every
106/// deleted `auto:*` fact, complete with its original `created_at`, and a
107/// curated store could not be kept clean.
108///
109/// The gate therefore lives here, at the store's own ingestion points, and not
110/// at the producers: a check placed at a call site only covers the call sites
111/// that exist when it is written, which is exactly how this defect arose.
112/// Session state itself is left untouched — it is ephemeral, capacity-capped,
113/// and backs handoff, session recap and metrics, none of which this key
114/// disables.
115pub(crate) fn machine_derived_writes_allowed() -> bool {
116    crate::core::auto_capture::is_enabled()
117}
118
119impl ProjectKnowledge {
120    /// Return the most recent active decision-like facts for session handoff.
121    /// Adds a pre-built fact, coalescing repeated observations into confirmations.
122    pub fn add_fact(&mut self, mut fact: KnowledgeFact) -> bool {
123        let trimmed_cat = fact.category.trim().to_string();
124        fact.category = trimmed_cat;
125        let trimmed_val = fact.value.trim().to_string();
126        fact.value = trimmed_val;
127        if fact.category.is_empty() || fact.value.is_empty() {
128            return false;
129        }
130        // #1802: refuse machine-derived facts while auto-capture is off. Placed
131        // before the coalescing branch below so a disabled run cannot even
132        // refresh `last_confirmed` on facts a previous enabled run left behind.
133        if is_machine_derived(&fact.category, &fact.key) && !machine_derived_writes_allowed() {
134            return false;
135        }
136
137        if let Some(existing) = self
138            .facts
139            .iter_mut()
140            .find(|existing| existing.category == fact.category && existing.value == fact.value)
141        {
142            if fact.last_confirmed > existing.last_confirmed {
143                existing.last_confirmed = fact.last_confirmed;
144            }
145            existing.confidence = existing.confidence.max(fact.confidence);
146            existing.confirmation_count = existing.confirmation_count.saturating_add(1);
147            existing.update_fidelity();
148        } else {
149            fact.update_fidelity();
150            self.facts.push(fact);
151            self.rebuild_index();
152        }
153
154        self.updated_at = Utc::now();
155        true
156    }
157
158    pub fn recent_decisions(&self, limit: usize) -> Vec<KnowledgeFact> {
159        let mut decisions: Vec<KnowledgeFact> = self
160            .facts
161            .iter()
162            .filter(|fact| {
163                let category = fact.category.to_ascii_lowercase();
164                fact.is_current()
165                    && (category.contains("decision")
166                        || category.contains("architecture")
167                        || category.contains("solution"))
168            })
169            .cloned()
170            .collect();
171        decisions.sort_by(|a, b| {
172            b.last_confirmed
173                .cmp(&a.last_confirmed)
174                .then_with(|| b.created_at.cmp(&a.created_at))
175        });
176        decisions.truncate(limit);
177        decisions
178    }
179    /// Keyword-based knowledge search across all facts.
180    /// Serves as the API surface for semantic retrieval; currently falls back
181    /// to substring matching. When the embedding model is loaded, this will
182    /// use HNSW vector search instead.
183    pub fn search_semantic(&self, query: &str, limit: usize) -> Vec<KnowledgeFact> {
184        let query_lower = query.to_lowercase();
185        let terms: Vec<&str> = query_lower.split_whitespace().collect();
186        if terms.is_empty() {
187            return Vec::new();
188        }
189        let mut scored: Vec<(usize, &KnowledgeFact)> = self
190            .facts
191            .iter()
192            .filter(|f| f.valid_until.is_none_or(|t| t > chrono::Utc::now()))
193            .map(|fact| {
194                let haystack = format!(
195                    "{} {} {}",
196                    fact.category.to_lowercase(),
197                    fact.value.to_lowercase(),
198                    fact.key.to_lowercase(),
199                );
200                let score = terms.iter().filter(|t| haystack.contains(*t)).count();
201                (score, fact)
202            })
203            .filter(|(score, _)| *score > 0)
204            .collect();
205        scored.sort_by_key(|a| std::cmp::Reverse(a.0));
206        scored
207            .into_iter()
208            .take(limit)
209            .map(|(_, f)| f.clone())
210            .collect()
211    }
212
213    pub fn list_project_roots() -> Result<Vec<String>, String> {
214        let base = crate::core::data_dir::lean_ctx_data_dir()?.join("knowledge");
215        if !base.exists() {
216            return Ok(Vec::new());
217        }
218
219        let mut roots = Vec::new();
220        let mut seen = HashSet::new();
221        let entries = std::fs::read_dir(&base).map_err(|e| e.to_string())?;
222        for entry in entries.flatten() {
223            let path = entry.path().join("knowledge.json");
224            if !path.is_file() {
225                continue;
226            }
227            let Ok(content) = std::fs::read_to_string(&path) else {
228                continue;
229            };
230            let Ok(knowledge) = serde_json::from_str::<Self>(&content) else {
231                continue;
232            };
233            if seen.insert(knowledge.project_root.clone()) {
234                roots.push(knowledge.project_root);
235            }
236        }
237
238        roots.sort();
239        Ok(roots)
240    }
241
242    pub fn save(&self) -> Result<(), String> {
243        let dir = knowledge_dir(&self.project_hash)?;
244        std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
245        #[cfg(unix)]
246        {
247            use std::os::unix::fs::PermissionsExt;
248            let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
249        }
250
251        let path = dir.join("knowledge.json");
252        let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
253        write_json_atomic(&dir, &path, &json)?;
254        Ok(())
255    }
256
257    /// Runs `f` while holding this project's locks — the in-process per-hash
258    /// mutex *and* the cross-process advisory file lock — without loading or
259    /// saving the knowledge JSON itself. [`mutate_locked`](Self::mutate_locked)
260    /// is built on this, and side-car stores that must stay consistent with the
261    /// facts (today: the embedding index) call it directly so their
262    /// read-modify-write is serialized against parallel
263    /// `remember`/`remove`/`reindex`. That side-car write used to run lock-free,
264    /// so concurrent callers clobbered each other's embeddings and pruned
265    /// just-stored vectors, degrading semantic recall (issue #412, a #326
266    /// follow-up).
267    pub(crate) fn with_project_lock<T>(project_root: &str, f: impl FnOnce() -> T) -> T {
268        let hash = hash_project_root(project_root);
269        let lock = knowledge_lock(&hash);
270        let _guard = lock
271            .lock()
272            .unwrap_or_else(std::sync::PoisonError::into_inner);
273
274        // Cross-process lock: create the dir up front so the lock file has a
275        // home, then block until any other process releases it. Held for the
276        // whole critical section via `_file_lock`'s lifetime.
277        let _file_lock = match knowledge_dir(&hash) {
278            Ok(dir) => {
279                let _ = std::fs::create_dir_all(&dir);
280                acquire_file_lock(&dir)
281            }
282            Err(_) => None,
283        };
284
285        f()
286    }
287
288    /// Runs a read-modify-write cycle under `with_project_lock`, then saves
289    /// atomically. The knowledge is (re)loaded *inside* the lock so
290    /// the closure always operates on the latest on-disk state; this is what
291    /// prevents lost updates when several `remember` calls run in parallel —
292    /// whether as threads in one process (parallel MCP calls) or as separate
293    /// processes (parallel CLI invocations, CLI + daemon + MCP server) — see
294    /// issue #326. Returns the persisted knowledge plus the closure's return
295    /// value so the caller can build a response from the committed state.
296    pub fn mutate_locked<T>(
297        project_root: &str,
298        f: impl FnOnce(&mut Self) -> T,
299    ) -> Result<(Self, T), String> {
300        Self::with_project_lock(project_root, || {
301            let mut knowledge = Self::load_or_create(project_root);
302            let out = f(&mut knowledge);
303            knowledge.save()?;
304            Ok((knowledge, out))
305        })
306    }
307
308    pub fn load(project_root: &str) -> Option<Self> {
309        let hash = hash_project_root(project_root);
310        let dir = knowledge_dir(&hash).ok()?;
311        let path = dir.join("knowledge.json");
312
313        if let Ok(content) = std::fs::read_to_string(&path) {
314            let size = content.len();
315            if size > 1_000_000 {
316                tracing::warn!(
317                    "knowledge.json is large ({:.1} MB) — recall may be slow. \
318                     Consider running ctx_knowledge(action=\"consolidate\") to compact it.",
319                    size as f64 / 1_048_576.0,
320                );
321            }
322            if let Ok(mut k) = serde_json::from_str::<Self>(&content) {
323                k.rebuild_index();
324                return Some(k);
325            }
326        }
327
328        let old_hash = crate::core::project_hash::hash_path_only(project_root);
329        if old_hash != hash {
330            crate::core::project_hash::migrate_if_needed(&old_hash, &hash, project_root);
331            if let Ok(content) = std::fs::read_to_string(&path)
332                && let Ok(mut k) = serde_json::from_str::<Self>(&content)
333            {
334                k.project_hash = hash;
335                k.rebuild_index();
336                let _ = k.save();
337                return Some(k);
338            }
339        }
340
341        // Migrate stores created before path normalization (issue #325): on
342        // Windows the CLI keyed its store by a backslash path, splitting it from
343        // the forward-slash MCP store. Pull any such legacy store into the
344        // canonical (normalized) location so facts converge.
345        for legacy_hash in crate::core::project_hash::legacy_unnormalized_hashes(project_root) {
346            if legacy_hash == hash {
347                continue;
348            }
349            crate::core::project_hash::migrate_if_needed(&legacy_hash, &hash, project_root);
350            if let Ok(content) = std::fs::read_to_string(&path)
351                && let Ok(mut k) = serde_json::from_str::<Self>(&content)
352            {
353                k.project_hash = hash;
354                k.rebuild_index();
355                let _ = k.save();
356                return Some(k);
357            }
358        }
359
360        None
361    }
362
363    pub fn load_or_create(project_root: &str) -> Self {
364        Self::load(project_root).unwrap_or_else(|| Self::new(project_root))
365    }
366
367    /// Migrates legacy knowledge that was accidentally stored under an empty project_root ("")
368    /// into the given `target_root`. Keeps a timestamped backup of the legacy file.
369    pub fn migrate_legacy_empty_root(
370        target_root: &str,
371        policy: &MemoryPolicy,
372    ) -> Result<bool, String> {
373        if target_root.trim().is_empty() {
374            return Ok(false);
375        }
376
377        let Some(legacy) = Self::load("") else {
378            return Ok(false);
379        };
380
381        if !legacy.project_root.trim().is_empty() {
382            return Ok(false);
383        }
384        if legacy.facts.is_empty() && legacy.patterns.is_empty() && legacy.history.is_empty() {
385            return Ok(false);
386        }
387
388        let mut target = Self::load_or_create(target_root);
389
390        fn fact_key(f: &KnowledgeFact) -> String {
391            format!(
392                "{}|{}|{}|{}|{}",
393                f.category, f.key, f.value, f.source_session, f.created_at
394            )
395        }
396        fn pattern_key(p: &ProjectPattern) -> String {
397            format!(
398                "{}|{}|{}|{}",
399                p.pattern_type, p.description, p.source_session, p.created_at
400            )
401        }
402        fn history_key(h: &ConsolidatedInsight) -> String {
403            format!(
404                "{}|{}|{}",
405                h.summary,
406                h.from_sessions.join(","),
407                h.timestamp
408            )
409        }
410
411        let mut seen_facts: std::collections::HashSet<String> =
412            target.facts.iter().map(fact_key).collect();
413        for f in legacy.facts {
414            if seen_facts.insert(fact_key(&f)) {
415                target.facts.push(f);
416            }
417        }
418
419        let mut seen_patterns: std::collections::HashSet<String> =
420            target.patterns.iter().map(pattern_key).collect();
421        for p in legacy.patterns {
422            if seen_patterns.insert(pattern_key(&p)) {
423                target.patterns.push(p);
424            }
425        }
426
427        let mut seen_history: std::collections::HashSet<String> =
428            target.history.iter().map(history_key).collect();
429        for h in legacy.history {
430            if seen_history.insert(history_key(&h)) {
431                target.history.push(h);
432            }
433        }
434
435        target.facts.sort_by(|a, b| {
436            b.created_at
437                .cmp(&a.created_at)
438                .then_with(|| b.confidence.total_cmp(&a.confidence))
439        });
440        if target.facts.len() > policy.knowledge.max_facts {
441            target.facts.truncate(policy.knowledge.max_facts);
442        }
443        target
444            .patterns
445            .sort_by_key(|x| std::cmp::Reverse(x.created_at));
446        if target.patterns.len() > policy.knowledge.max_patterns {
447            target.patterns.truncate(policy.knowledge.max_patterns);
448        }
449        target
450            .history
451            .sort_by_key(|x| std::cmp::Reverse(x.timestamp));
452        if target.history.len() > policy.knowledge.max_history {
453            target.history.truncate(policy.knowledge.max_history);
454        }
455
456        target.updated_at = Utc::now();
457        target.save()?;
458
459        let legacy_hash = crate::core::project_hash::hash_path_only("");
460        let legacy_dir = knowledge_dir(&legacy_hash)?;
461        let legacy_path = legacy_dir.join("knowledge.json");
462        if legacy_path.exists() {
463            let ts = Utc::now().format("%Y%m%d-%H%M%S");
464            let backup = legacy_dir.join(format!("knowledge.legacy-empty-root.{ts}.json"));
465            std::fs::rename(&legacy_path, &backup).map_err(|e| e.to_string())?;
466        }
467
468        Ok(true)
469    }
470}
471
472#[cfg(test)]
473mod tests {
474    use super::*;
475    use fs2::FileExt;
476
477    // --- #1802: `auto_capture = false` must hold at the store, not the callers ---
478
479    fn machine_fact(category: &str, key: &str) -> KnowledgeFact {
480        let now = chrono::Utc::now();
481        KnowledgeFact {
482            category: category.to_string(),
483            key: key.to_string(),
484            value: "Finding: run-guards.ts: Read run-guards.ts (92L)".to_string(),
485            source_session: "session-1".to_string(),
486            confidence: 0.8,
487            created_at: now,
488            last_confirmed: now,
489            retrieval_count: 0,
490            last_retrieved: None,
491            valid_from: None,
492            valid_until: None,
493            supersedes: None,
494            confirmation_count: 1,
495            feedback_up: 0,
496            feedback_down: 0,
497            last_feedback: None,
498            privacy: Default::default(),
499            sensitivity: Default::default(),
500            imported_from: None,
501            archetype: Default::default(),
502            fidelity: None,
503            revision_count: 0,
504        }
505    }
506
507    #[test]
508    fn machine_derived_is_recognised_in_either_ingestion_shape() {
509        // `extract_session_facts` marks the category; `auto_capture` marks the
510        // key. Both producers must be recognisable by one predicate.
511        assert!(is_machine_derived("auto:blocker", "run-guards.ts"));
512        assert!(is_machine_derived("blocker", "auto:config.rs"));
513        assert!(!is_machine_derived("konventionen", "naming"));
514        assert!(!is_machine_derived("ops", "deploy"));
515    }
516
517    #[test]
518    fn a_curated_fact_is_never_affected_by_the_gate() {
519        // The key disables *automatic* capture. A fact a person wrote must be
520        // storable whatever the flag says, or the feature would be a footgun.
521        let mut knowledge = ProjectKnowledge::new("/tmp/project");
522        assert!(
523            knowledge.add_fact(machine_fact("konventionen", "naming")),
524            "curated facts must always be accepted"
525        );
526    }
527
528    #[test]
529    fn disabled_capture_blocks_every_machine_derived_shape() {
530        // The regression: a single MCP call re-materialised deleted `auto:*`
531        // facts because only one of two producers consulted the flag. Asserting
532        // at the store covers both, and any producer added later.
533        let _env = crate::core::data_dir::test_env_lock();
534        crate::test_env::set_var("LEAN_CTX_AUTO_CAPTURE", "0");
535
536        let mut knowledge = ProjectKnowledge::new("/tmp/project");
537        let category_marked = knowledge.add_fact(machine_fact("auto:blocker", "run-guards.ts"));
538        let key_marked = knowledge.add_fact(machine_fact("blocker", "auto:config.rs"));
539
540        crate::test_env::remove_var("LEAN_CTX_AUTO_CAPTURE");
541
542        assert!(!category_marked, "auto:* category must be refused");
543        assert!(!key_marked, "auto:* key must be refused");
544        assert!(
545            knowledge.facts.is_empty(),
546            "nothing machine-derived may reach the durable store"
547        );
548    }
549
550    #[test]
551    fn enabled_capture_still_stores_machine_derived_facts() {
552        let _env = crate::core::data_dir::test_env_lock();
553        crate::test_env::set_var("LEAN_CTX_AUTO_CAPTURE", "1");
554
555        let mut knowledge = ProjectKnowledge::new("/tmp/project");
556        let stored = knowledge.add_fact(machine_fact("auto:blocker", "run-guards.ts"));
557
558        crate::test_env::remove_var("LEAN_CTX_AUTO_CAPTURE");
559
560        assert!(stored, "the default behaviour must be unchanged");
561    }
562
563    #[test]
564    fn disabled_capture_does_not_refresh_existing_machine_facts() {
565        // Facts from an earlier enabled run stay on disk — the fix stops new
566        // writes, it does not delete history. But a disabled run must not keep
567        // touching them either, or they would look perpetually fresh to the
568        // lifecycle and never age out.
569        let _env = crate::core::data_dir::test_env_lock();
570        crate::test_env::set_var("LEAN_CTX_AUTO_CAPTURE", "1");
571        let mut knowledge = ProjectKnowledge::new("/tmp/project");
572        knowledge.add_fact(machine_fact("auto:blocker", "run-guards.ts"));
573        let confirmed_while_enabled = knowledge.facts[0].last_confirmed;
574
575        crate::test_env::set_var("LEAN_CTX_AUTO_CAPTURE", "0");
576        let refreshed = knowledge.add_fact(machine_fact("auto:blocker", "run-guards.ts"));
577        crate::test_env::remove_var("LEAN_CTX_AUTO_CAPTURE");
578
579        assert!(!refreshed);
580        assert_eq!(knowledge.facts.len(), 1);
581        assert_eq!(
582            knowledge.facts[0].last_confirmed, confirmed_while_enabled,
583            "a refused write must not refresh the existing fact"
584        );
585    }
586
587    #[test]
588    fn file_lock_is_exclusive_across_handles() {
589        // flock-style locks are tied to the open file description, so two
590        // independent `open()`s in the same process behave like two separate
591        // processes: while the first holds the exclusive lock, the second must
592        // fail to acquire it. This validates the cross-process guarantee that
593        // protects parallel CLI writes (issue #326).
594        let dir = tempfile::tempdir().unwrap();
595        let held = acquire_file_lock(dir.path()).expect("first lock must succeed");
596
597        let second = std::fs::OpenOptions::new()
598            .create(true)
599            .truncate(false)
600            .write(true)
601            .open(dir.path().join(".knowledge.lock"))
602            .unwrap();
603        assert!(
604            second.try_lock_exclusive().is_err(),
605            "a second handle must not acquire the lock while it is held"
606        );
607
608        drop(held);
609        // `close()` releases the flock synchronously, so the lock IS free here.
610        // Under heavy parallel test load, however, a single non-blocking
611        // `try_lock_exclusive()` can momentarily observe `EWOULDBLOCK` from
612        // scheduling jitter. A short bounded retry removes that flake without
613        // weakening the guarantee: the lock must become acquirable again.
614        let mut reacquired = false;
615        for _ in 0..50 {
616            if second.try_lock_exclusive().is_ok() {
617                reacquired = true;
618                break;
619            }
620            std::thread::sleep(std::time::Duration::from_millis(10));
621        }
622        assert!(
623            reacquired,
624            "lock must be acquirable within 500ms of release"
625        );
626    }
627
628    #[test]
629    fn write_json_atomic_leaves_valid_file_and_no_temp() {
630        let dir = tempfile::tempdir().unwrap();
631        let path = dir.path().join("knowledge.json");
632        write_json_atomic(dir.path(), &path, "{\"ok\":true}").unwrap();
633        assert_eq!(std::fs::read_to_string(&path).unwrap(), "{\"ok\":true}");
634        let leftover = std::fs::read_dir(dir.path())
635            .unwrap()
636            .filter_map(Result::ok)
637            .any(|e| e.file_name().to_string_lossy().contains(".tmp."));
638        assert!(!leftover, "no temp file should remain");
639    }
640
641    #[test]
642    fn load_rebuilds_ephemeral_index_without_changing_json() {
643        let _isolated = crate::core::data_dir::isolated_data_dir();
644        let root = "/tmp/knowledge-index-load";
645        let policy = MemoryPolicy::default();
646        let mut knowledge = ProjectKnowledge::new(root);
647        knowledge.remember(
648            "architecture",
649            "database",
650            "PostgreSQL",
651            "test",
652            0.9,
653            &policy,
654        );
655        knowledge.save().unwrap();
656
657        let loaded = ProjectKnowledge::load(root).expect("saved knowledge should load");
658        assert!(loaded.index.token_positions.contains_key("postgresql"));
659        assert_eq!(loaded.recall("postgresql").len(), 1);
660
661        let json = serde_json::to_string(&loaded).unwrap();
662        assert!(!json.contains("\"index\""));
663    }
664}