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    use std::io::Write;
66    let mut tmp =
67        tempfile::NamedTempFile::new_in(dir).map_err(|_| "knowledge temporary file unavailable")?;
68    tmp.write_all(json.as_bytes())
69        .map_err(|_| "knowledge write failed")?;
70    tmp.persist(path)
71        .map_err(|_| "knowledge publication failed")?;
72    Ok(())
73}
74
75/// Marker that identifies a fact as machine-derived rather than curated.
76///
77/// Both automatic producers already carry it: `extract_session_facts` tags the
78/// *category* (`auto:decision`, `auto:pattern`, `auto:blocker`) and
79/// `auto_capture` derives an `auto:`-prefixed *key*. Nothing a person writes
80/// through `ctx_knowledge(action="remember")` does.
81pub(crate) const MACHINE_DERIVED_PREFIX: &str = "auto:";
82
83/// Whether this fact was derived by lean-ctx rather than written by a person.
84pub(crate) fn is_machine_derived(category: &str, key: &str) -> bool {
85    category.trim_start().starts_with(MACHINE_DERIVED_PREFIX)
86        || key.trim_start().starts_with(MACHINE_DERIVED_PREFIX)
87}
88
89/// Whether a machine-derived fact may enter the durable store right now.
90///
91/// #1802: `auto_capture = false` was honoured by exactly one producer
92/// (`auto_capture::capture_finding`) and ignored by the other
93/// (`extract_session_facts`, reached from both the consolidation engine and
94/// the session *save* path) — so a single MCP call re-materialised every
95/// deleted `auto:*` fact, complete with its original `created_at`, and a
96/// curated store could not be kept clean.
97///
98/// The gate therefore lives here, at the store's own ingestion points, and not
99/// at the producers: a check placed at a call site only covers the call sites
100/// that exist when it is written, which is exactly how this defect arose.
101/// Session state itself is left untouched — it is ephemeral, capacity-capped,
102/// and backs handoff, session recap and metrics, none of which this key
103/// disables.
104pub(crate) fn machine_derived_writes_allowed() -> bool {
105    crate::core::auto_capture::is_enabled()
106}
107
108impl ProjectKnowledge {
109    /// Return the most recent active decision-like facts for session handoff.
110    /// Adds a pre-built fact, coalescing repeated observations into confirmations.
111    pub fn add_fact(&mut self, mut fact: KnowledgeFact) -> bool {
112        let trimmed_cat = fact.category.trim().to_string();
113        fact.category = trimmed_cat;
114        let trimmed_val = fact.value.trim().to_string();
115        fact.value = trimmed_val;
116        if fact.category.is_empty() || fact.value.is_empty() {
117            return false;
118        }
119        // #1802: refuse machine-derived facts while auto-capture is off. Placed
120        // before the coalescing branch below so a disabled run cannot even
121        // refresh `last_confirmed` on facts a previous enabled run left behind.
122        if is_machine_derived(&fact.category, &fact.key) && !machine_derived_writes_allowed() {
123            return false;
124        }
125        // Same store boundary as `remember_with_origin` (G5, E3).
126        let Some([category, key, value]) =
127            super::core::admit_fact_fields([&fact.category, &fact.key, &fact.value])
128        else {
129            return false;
130        };
131        (fact.category, fact.key, fact.value) = (category, key, value);
132
133        if let Some(existing) = self.facts.iter_mut().find(|existing| {
134            existing.category == fact.category
135                && existing.value == fact.value
136                && existing.origin == fact.origin
137        }) {
138            if fact.last_confirmed > existing.last_confirmed {
139                existing.last_confirmed = fact.last_confirmed;
140            }
141            existing.confidence = existing.confidence.max(fact.confidence);
142            existing.confirmation_count = existing.confirmation_count.saturating_add(1);
143            existing.update_fidelity();
144        } else {
145            fact.update_fidelity();
146            self.facts.push(fact);
147            self.rebuild_index();
148        }
149
150        self.updated_at = Utc::now();
151        true
152    }
153
154    pub fn recent_decisions(&self, limit: usize) -> Vec<KnowledgeFact> {
155        let mut decisions: Vec<KnowledgeFact> = self
156            .facts
157            .iter()
158            .filter(|fact| {
159                let category = fact.category.to_ascii_lowercase();
160                fact.is_current()
161                    && (category.contains("decision")
162                        || category.contains("architecture")
163                        || category.contains("solution"))
164            })
165            .cloned()
166            .collect();
167        decisions.sort_by(|a, b| {
168            b.last_confirmed
169                .cmp(&a.last_confirmed)
170                .then_with(|| b.created_at.cmp(&a.created_at))
171        });
172        decisions.truncate(limit);
173        decisions
174    }
175    /// Keyword-based knowledge search across all facts.
176    /// Serves as the API surface for semantic retrieval; currently falls back
177    /// to substring matching. When the embedding model is loaded, this will
178    /// use HNSW vector search instead.
179    pub fn search_semantic(&self, query: &str, limit: usize) -> Vec<KnowledgeFact> {
180        let query_lower = query.to_lowercase();
181        let terms: Vec<&str> = query_lower.split_whitespace().collect();
182        if terms.is_empty() {
183            return Vec::new();
184        }
185        let mut scored: Vec<(usize, &KnowledgeFact)> = self
186            .facts
187            .iter()
188            .filter(|f| f.valid_until.is_none_or(|t| t > chrono::Utc::now()))
189            .map(|fact| {
190                let haystack = format!(
191                    "{} {} {}",
192                    fact.category.to_lowercase(),
193                    fact.value.to_lowercase(),
194                    fact.key.to_lowercase(),
195                );
196                let score = terms.iter().filter(|t| haystack.contains(*t)).count();
197                (score, fact)
198            })
199            .filter(|(score, _)| *score > 0)
200            .collect();
201        scored.sort_by_key(|a| std::cmp::Reverse(a.0));
202        scored
203            .into_iter()
204            .take(limit)
205            .map(|(_, f)| f.clone())
206            .collect()
207    }
208
209    pub fn list_project_roots() -> Result<Vec<String>, String> {
210        let base = crate::core::data_dir::lean_ctx_data_dir()?.join("knowledge");
211        if !base.exists() {
212            return Ok(Vec::new());
213        }
214
215        let mut roots = Vec::new();
216        let mut seen = HashSet::new();
217        let entries = std::fs::read_dir(&base).map_err(|e| e.to_string())?;
218        for entry in entries.flatten() {
219            let path = entry.path().join("knowledge.json");
220            if !path.is_file() {
221                continue;
222            }
223            let Ok(content) = std::fs::read_to_string(&path) else {
224                continue;
225            };
226            let Ok(knowledge) = serde_json::from_str::<Self>(&content) else {
227                continue;
228            };
229            if seen.insert(knowledge.project_root.clone()) {
230                roots.push(knowledge.project_root);
231            }
232        }
233
234        roots.sort();
235        Ok(roots)
236    }
237
238    /// Optional capture must not trigger legacy migration writes during a read,
239    /// or replace an unreadable existing store with a newly created empty one.
240    pub(crate) fn load_for_checked_capture(project_root: &str) -> Result<Self, String> {
241        let hash = hash_project_root(project_root);
242        let path = knowledge_dir(&hash)?.join("knowledge.json");
243        match std::fs::symlink_metadata(&path) {
244            Ok(_) => {
245                let text = crate::core::policy::diagnostics::Target::read_file(&path)
246                    .ok_or("knowledge input is unavailable or uninspectable")?;
247                let mut knowledge: Self =
248                    serde_json::from_str(&text).map_err(|_| "knowledge input is invalid")?;
249                let canonical = |root: &str| {
250                    crate::core::pathutil::safe_canonicalize_bounded(Path::new(root), 2000)
251                };
252                if knowledge.project_hash != hash
253                    || canonical(&knowledge.project_root) != canonical(project_root)
254                {
255                    return Err("knowledge input belongs to a different project".into());
256                }
257                knowledge.rebuild_index();
258                return Ok(knowledge);
259            }
260            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
261            Err(_) => return Err("knowledge input metadata unavailable".into()),
262        }
263        let mut legacy = crate::core::project_hash::legacy_unnormalized_hashes(project_root);
264        legacy.push(crate::core::project_hash::hash_path_only(project_root));
265        for old_hash in legacy.into_iter().filter(|old| old != &hash) {
266            match std::fs::symlink_metadata(knowledge_dir(&old_hash)?.join("knowledge.json")) {
267                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
268                _ => return Err("knowledge requires an explicit legacy migration".into()),
269            }
270        }
271        Ok(Self::new(project_root))
272    }
273
274    pub(crate) fn save_policy_checked(
275        &self,
276        source_tool: &str,
277        original_content: &str,
278    ) -> Result<(), String> {
279        let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
280        if let Some(policy) =
281            crate::core::policy::runtime::for_project(Path::new(&self.project_root))?
282        {
283            if !policy.tool_allowed("ctx_knowledge")
284                || !policy.tool_allowed(source_tool)
285                || crate::core::policy::content::evaluate_text(original_content, &policy).blocked
286                || json.len() > crate::core::policy::content::MAX_PROTECTED_CONTENT_BYTES
287            {
288                return Err("knowledge persistence withheld by policy".into());
289            }
290            let original: serde_json::Value =
291                serde_json::from_str(&json).map_err(|_| "knowledge is not inspectable")?;
292            if crate::core::policy::diagnostics::inspect(&original, Some(&policy)).as_ref()
293                != Some(&original)
294            {
295                // Preserve structural identity and old customer data. Writers
296                // must supply already-safe facts; never silently rewrite keys
297                // or republish an unsafe legacy store into a temporary file.
298                return Err("knowledge persistence requires policy-safe fields".into());
299            }
300        }
301        self.save_unlocked()
302    }
303
304    pub fn save(&self) -> Result<(), String> {
305        super::protection::current(&self.project_root)?;
306        Self::with_project_lock_checked(&self.project_root, || self.save_unlocked())?
307    }
308
309    fn save_unlocked(&self) -> Result<(), String> {
310        if self.withheld.is_empty() {
311            return self.save_complete_unlocked();
312        }
313        let existing = Self::load_for_checked_capture(&self.project_root)?;
314        let complete = self.complete_for_storage(&existing)?;
315        complete.save_complete_unlocked()
316    }
317
318    fn save_complete_unlocked(&self) -> Result<(), String> {
319        let current = super::protection::current(&self.project_root)?;
320        let safe;
321        let candidate = if let Some(policy) = &current {
322            if self.project_hash != hash_project_root(&self.project_root) {
323                return Err("knowledge storage identity mismatch".into());
324            }
325            let existing = Self::load_for_checked_capture(&self.project_root)?;
326            super::protection::require_safe(&existing, policy)?;
327            safe = super::protection::view(self, policy)?;
328            &safe
329        } else {
330            self
331        };
332        let dir = knowledge_dir(&self.project_hash)?;
333        std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
334        #[cfg(unix)]
335        {
336            use std::os::unix::fs::PermissionsExt;
337            let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
338        }
339
340        let path = dir.join("knowledge.json");
341        let json = serde_json::to_string_pretty(candidate).map_err(|e| e.to_string())?;
342        if let Some(policy) = super::protection::current(&self.project_root)? {
343            super::protection::require_safe(candidate, &policy)?;
344        }
345        write_json_atomic(&dir, &path, &json)?;
346        Ok(())
347    }
348
349    /// Runs `f` while holding this project's locks — the in-process per-hash
350    /// mutex *and* the cross-process advisory file lock — without loading or
351    /// saving the knowledge JSON itself. [`mutate_locked`](Self::mutate_locked)
352    /// is built on this, and side-car stores that must stay consistent with the
353    /// facts (today: the embedding index) call it directly so their
354    /// read-modify-write is serialized against parallel
355    /// `remember`/`remove`/`reindex`. That side-car write used to run lock-free,
356    /// so concurrent callers clobbered each other's embeddings and pruned
357    /// just-stored vectors, degrading semantic recall (issue #412, a #326
358    /// follow-up).
359    pub(crate) fn with_project_lock<T>(project_root: &str, f: impl FnOnce() -> T) -> T {
360        let hash = hash_project_root(project_root);
361        let lock = knowledge_lock(&hash);
362        let _guard = lock
363            .lock()
364            .unwrap_or_else(std::sync::PoisonError::into_inner);
365
366        // Cross-process lock: create the dir up front so the lock file has a
367        // home, then block until any other process releases it. Held for the
368        // whole critical section via `_file_lock`'s lifetime.
369        let _file_lock = match knowledge_dir(&hash) {
370            Ok(dir) => {
371                let _ = std::fs::create_dir_all(&dir);
372                acquire_file_lock(&dir)
373            }
374            Err(_) => None,
375        };
376
377        f()
378    }
379
380    /// Runs a read-modify-write cycle under `with_project_lock`, then saves
381    /// atomically. The knowledge is (re)loaded *inside* the lock so
382    /// the closure always operates on the latest on-disk state; this is what
383    /// prevents lost updates when several `remember` calls run in parallel —
384    /// whether as threads in one process (parallel MCP calls) or as separate
385    /// processes (parallel CLI invocations, CLI + daemon + MCP server) — see
386    /// issue #326. Returns the persisted knowledge plus the closure's return
387    /// value so the caller can build a response from the committed state.
388    pub(crate) fn with_project_lock_checked<T>(
389        project_root: &str,
390        f: impl FnOnce() -> T,
391    ) -> Result<T, String> {
392        use fs2::FileExt;
393        let hash = hash_project_root(project_root);
394        let lock = knowledge_lock(&hash);
395        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
396        let _guard = loop {
397            match lock.try_lock() {
398                Ok(guard) => break guard,
399                Err(std::sync::TryLockError::WouldBlock)
400                    if std::time::Instant::now() < deadline =>
401                {
402                    std::thread::sleep(std::time::Duration::from_millis(5));
403                }
404                Err(_) => return Err("knowledge lock unavailable".into()),
405            }
406        };
407        let dir = knowledge_dir(&hash)?;
408        std::fs::create_dir_all(&dir).map_err(|_| "knowledge directory unavailable")?;
409        let file = crate::core::policy::diagnostics::open_append(&dir.join(".knowledge.lock"))
410            .map_err(|_| "knowledge file lock unavailable")?;
411        loop {
412            match file.try_lock_exclusive() {
413                Ok(()) => break,
414                Err(e)
415                    if crate::core::file_lock::is_contended(&e)
416                        && std::time::Instant::now() < deadline =>
417                {
418                    std::thread::sleep(std::time::Duration::from_millis(5));
419                }
420                Err(_) => return Err("knowledge file lock unavailable".into()),
421            }
422        }
423        let output = f();
424        let _ = FileExt::unlock(&file);
425        Ok(output)
426    }
427
428    pub fn mutate_locked<T>(
429        project_root: &str,
430        f: impl FnOnce(&mut Self) -> T,
431    ) -> Result<(Self, T), String> {
432        crate::core::providers::provenance::with_reuse_deadline(|| {
433            Self::mutate_locked_in_scope(project_root, f)
434        })
435    }
436
437    fn mutate_locked_in_scope<T>(
438        project_root: &str,
439        f: impl FnOnce(&mut Self) -> T,
440    ) -> Result<(Self, T), String> {
441        super::protection::current(project_root)?;
442        Self::with_project_lock_checked(project_root, || {
443            let active = super::protection::current(project_root)?;
444            let mut knowledge = if let Some(policy) = &active {
445                let raw = Self::load_for_checked_capture(project_root)?;
446                super::protection::require_safe(&raw, policy)?;
447                raw
448            } else {
449                Self::load_or_create(project_root)
450            };
451            knowledge = knowledge.admit_sources();
452            crate::core::policy::runtime::REQUEST_PROJECT.sync_scope(
453                std::cell::RefCell::new(Some(PathBuf::from(project_root))),
454                || {
455                    let out = f(&mut knowledge);
456                    if let Some(policy) = super::protection::current(project_root)? {
457                        knowledge = super::protection::view(&knowledge, &policy)?;
458                    }
459                    knowledge.save_unlocked()?;
460                    Ok((knowledge.admit_sources(), out))
461                },
462            )
463        })?
464    }
465
466    pub fn load(project_root: &str) -> Option<Self> {
467        match super::protection::current(project_root) {
468            Ok(Some(_)) => {
469                let path = knowledge_dir(&hash_project_root(project_root))
470                    .ok()?
471                    .join("knowledge.json");
472                std::fs::symlink_metadata(path).ok()?;
473                let raw = Self::load_for_checked_capture(project_root).ok()?;
474                return match super::protection::current(project_root).ok()? {
475                    Some(policy) => super::protection::view(&raw, &policy)
476                        .ok()
477                        .map(Self::admit_sources),
478                    None => Some(raw.admit_sources()),
479                };
480            }
481            Err(_) => return None,
482            Ok(None) => {}
483        }
484        let hash = hash_project_root(project_root);
485        let dir = knowledge_dir(&hash).ok()?;
486        let path = dir.join("knowledge.json");
487
488        if let Ok(content) = std::fs::read_to_string(&path) {
489            let size = content.len();
490            if size > 1_000_000 {
491                tracing::warn!(
492                    "knowledge.json is large ({:.1} MB) — recall may be slow. \
493                     Consider running ctx_knowledge(action=\"consolidate\") to compact it.",
494                    size as f64 / 1_048_576.0,
495                );
496            }
497            if let Ok(mut k) = serde_json::from_str::<Self>(&content) {
498                k.rebuild_index();
499                return Some(k.admit_sources());
500            }
501        }
502
503        let old_hash = crate::core::project_hash::hash_path_only(project_root);
504        if old_hash != hash {
505            crate::core::project_hash::migrate_if_needed(&old_hash, &hash, project_root);
506            if let Ok(content) = std::fs::read_to_string(&path)
507                && let Ok(mut k) = serde_json::from_str::<Self>(&content)
508            {
509                k.project_hash = hash;
510                k.rebuild_index();
511                let _ = k.save_unlocked();
512                return Some(k.admit_sources());
513            }
514        }
515
516        // Migrate stores created before path normalization (issue #325): on
517        // Windows the CLI keyed its store by a backslash path, splitting it from
518        // the forward-slash MCP store. Pull any such legacy store into the
519        // canonical (normalized) location so facts converge.
520        for legacy_hash in crate::core::project_hash::legacy_unnormalized_hashes(project_root) {
521            if legacy_hash == hash {
522                continue;
523            }
524            crate::core::project_hash::migrate_if_needed(&legacy_hash, &hash, project_root);
525            if let Ok(content) = std::fs::read_to_string(&path)
526                && let Ok(mut k) = serde_json::from_str::<Self>(&content)
527            {
528                k.project_hash = hash;
529                k.rebuild_index();
530                let _ = k.save_unlocked();
531                return Some(k.admit_sources());
532            }
533        }
534
535        None
536    }
537
538    pub fn load_or_create(project_root: &str) -> Self {
539        Self::load(project_root).unwrap_or_else(|| Self::new(project_root))
540    }
541
542    /// Migrates legacy knowledge that was accidentally stored under an empty project_root ("")
543    /// into the given `target_root`. Keeps a timestamped backup of the legacy file.
544    pub fn migrate_legacy_empty_root(
545        target_root: &str,
546        policy: &MemoryPolicy,
547    ) -> Result<bool, String> {
548        if target_root.trim().is_empty() {
549            return Ok(false);
550        }
551
552        if super::protection::current(target_root)?.is_some() {
553            return Err("unscoped legacy knowledge requires explicit protected migration".into());
554        }
555        // This explicit compatibility migration may read the old empty-root
556        // store, but general load/save must never treat an empty root as authority.
557        let mut legacy_store = None;
558        for hash in [
559            hash_project_root(""),
560            crate::core::project_hash::hash_path_only(""),
561        ] {
562            let path = knowledge_dir(&hash)?.join("knowledge.json");
563            match std::fs::symlink_metadata(&path) {
564                Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
565                Err(_) => return Err("legacy knowledge input unavailable".into()),
566                Ok(_) => {}
567            }
568            let text = crate::core::policy::diagnostics::Target::read_file(&path)
569                .ok_or("legacy knowledge input is uninspectable")?;
570            let legacy: Self =
571                serde_json::from_str(&text).map_err(|_| "invalid legacy knowledge")?;
572            legacy_store = Some((legacy, path));
573            break;
574        }
575        let Some((legacy, legacy_path)) = legacy_store else {
576            return Ok(false);
577        };
578
579        if !legacy.project_root.trim().is_empty() {
580            return Ok(false);
581        }
582        if legacy.facts.is_empty() && legacy.patterns.is_empty() && legacy.history.is_empty() {
583            return Ok(false);
584        }
585
586        Self::with_project_lock_checked(target_root, || {
587            if super::protection::current(target_root)?.is_some() {
588                return Err("legacy migration withheld by changed project policy".into());
589            }
590            let mut target = Self::load_or_create(target_root);
591
592            fn fact_key(f: &KnowledgeFact) -> String {
593                format!(
594                    "{}|{}|{}|{}|{}",
595                    f.category, f.key, f.value, f.source_session, f.created_at
596                )
597            }
598            fn pattern_key(p: &ProjectPattern) -> String {
599                format!(
600                    "{}|{}|{}|{}",
601                    p.pattern_type, p.description, p.source_session, p.created_at
602                )
603            }
604            fn history_key(h: &ConsolidatedInsight) -> String {
605                format!(
606                    "{}|{}|{}",
607                    h.summary,
608                    h.from_sessions.join(","),
609                    h.timestamp
610                )
611            }
612
613            let mut seen_facts: std::collections::HashSet<String> =
614                target.facts.iter().map(fact_key).collect();
615            for f in legacy.facts {
616                if seen_facts.insert(fact_key(&f)) {
617                    target.facts.push(f);
618                }
619            }
620
621            let mut seen_patterns: std::collections::HashSet<String> =
622                target.patterns.iter().map(pattern_key).collect();
623            for p in legacy.patterns {
624                if seen_patterns.insert(pattern_key(&p)) {
625                    target.patterns.push(p);
626                }
627            }
628
629            let mut seen_history: std::collections::HashSet<String> =
630                target.history.iter().map(history_key).collect();
631            for h in legacy.history {
632                if seen_history.insert(history_key(&h)) {
633                    target.history.push(h);
634                }
635            }
636
637            target.facts.sort_by(|a, b| {
638                b.created_at
639                    .cmp(&a.created_at)
640                    .then_with(|| b.confidence.total_cmp(&a.confidence))
641            });
642            if target.facts.len() > policy.knowledge.max_facts {
643                target.facts.truncate(policy.knowledge.max_facts);
644            }
645            target
646                .patterns
647                .sort_by_key(|x| std::cmp::Reverse(x.created_at));
648            if target.patterns.len() > policy.knowledge.max_patterns {
649                target.patterns.truncate(policy.knowledge.max_patterns);
650            }
651            target
652                .history
653                .sort_by_key(|x| std::cmp::Reverse(x.timestamp));
654            if target.history.len() > policy.knowledge.max_history {
655                target.history.truncate(policy.knowledge.max_history);
656            }
657
658            target.updated_at = Utc::now();
659            if super::protection::current(target_root)?.is_some() {
660                return Err("legacy migration withheld by changed project policy".into());
661            }
662            target.save_unlocked()?;
663
664            let legacy_dir = legacy_path.parent().ok_or("legacy directory unavailable")?;
665            if legacy_path.exists() {
666                let ts = Utc::now().format("%Y%m%d-%H%M%S");
667                let backup = legacy_dir.join(format!("knowledge.legacy-empty-root.{ts}.json"));
668                std::fs::hard_link(&legacy_path, &backup)
669                    .map_err(|_| "legacy backup could not be preserved")?;
670                std::fs::remove_file(&legacy_path)
671                    .map_err(|_| "legacy backup retained but source cleanup failed")?;
672            }
673
674            Ok(true)
675        })?
676    }
677}
678
679#[cfg(test)]
680mod tests {
681    use super::*;
682    use fs2::FileExt;
683
684    // --- #1802: `auto_capture = false` must hold at the store, not the callers ---
685
686    fn machine_fact(category: &str, key: &str) -> KnowledgeFact {
687        let now = chrono::Utc::now();
688        KnowledgeFact {
689            origin: crate::core::knowledge::FactOrigin::Local,
690            category: category.to_string(),
691            key: key.to_string(),
692            value: "Finding: run-guards.ts: Read run-guards.ts (92L)".to_string(),
693            source_session: "session-1".to_string(),
694            confidence: 0.8,
695            created_at: now,
696            last_confirmed: now,
697            retrieval_count: 0,
698            last_retrieved: None,
699            valid_from: None,
700            valid_until: None,
701            supersedes: None,
702            confirmation_count: 1,
703            feedback_up: 0,
704            feedback_down: 0,
705            last_feedback: None,
706            privacy: Default::default(),
707            sensitivity: Default::default(),
708            imported_from: None,
709            archetype: Default::default(),
710            fidelity: None,
711            revision_count: 0,
712        }
713    }
714
715    #[test]
716    fn machine_derived_is_recognised_in_either_ingestion_shape() {
717        // `extract_session_facts` marks the category; `auto_capture` marks the
718        // key. Both producers must be recognisable by one predicate.
719        assert!(is_machine_derived("auto:blocker", "run-guards.ts"));
720        assert!(is_machine_derived("blocker", "auto:config.rs"));
721        assert!(!is_machine_derived("konventionen", "naming"));
722        assert!(!is_machine_derived("ops", "deploy"));
723    }
724
725    #[test]
726    fn a_curated_fact_is_never_affected_by_the_gate() {
727        // The key disables *automatic* capture. A fact a person wrote must be
728        // storable whatever the flag says, or the feature would be a footgun.
729        let mut knowledge = ProjectKnowledge::new("/tmp/project");
730        assert!(
731            knowledge.add_fact(machine_fact("konventionen", "naming")),
732            "curated facts must always be accepted"
733        );
734    }
735
736    #[test]
737    fn disabled_capture_blocks_every_machine_derived_shape() {
738        // The regression: a single MCP call re-materialised deleted `auto:*`
739        // facts because only one of two producers consulted the flag. Asserting
740        // at the store covers both, and any producer added later.
741        let _env = crate::core::data_dir::test_env_lock();
742        crate::test_env::set_var("LEAN_CTX_AUTO_CAPTURE", "0");
743
744        let mut knowledge = ProjectKnowledge::new("/tmp/project");
745        let category_marked = knowledge.add_fact(machine_fact("auto:blocker", "run-guards.ts"));
746        let key_marked = knowledge.add_fact(machine_fact("blocker", "auto:config.rs"));
747
748        crate::test_env::remove_var("LEAN_CTX_AUTO_CAPTURE");
749
750        assert!(!category_marked, "auto:* category must be refused");
751        assert!(!key_marked, "auto:* key must be refused");
752        assert!(
753            knowledge.facts.is_empty(),
754            "nothing machine-derived may reach the durable store"
755        );
756    }
757
758    #[test]
759    fn enabled_capture_still_stores_machine_derived_facts() {
760        let _env = crate::core::data_dir::test_env_lock();
761        crate::test_env::set_var("LEAN_CTX_AUTO_CAPTURE", "1");
762
763        let mut knowledge = ProjectKnowledge::new("/tmp/project");
764        let stored = knowledge.add_fact(machine_fact("auto:blocker", "run-guards.ts"));
765
766        crate::test_env::remove_var("LEAN_CTX_AUTO_CAPTURE");
767
768        assert!(stored, "the default behaviour must be unchanged");
769    }
770
771    #[test]
772    fn disabled_capture_does_not_refresh_existing_machine_facts() {
773        // Facts from an earlier enabled run stay on disk — the fix stops new
774        // writes, it does not delete history. But a disabled run must not keep
775        // touching them either, or they would look perpetually fresh to the
776        // lifecycle and never age out.
777        let _env = crate::core::data_dir::test_env_lock();
778        crate::test_env::set_var("LEAN_CTX_AUTO_CAPTURE", "1");
779        let mut knowledge = ProjectKnowledge::new("/tmp/project");
780        knowledge.add_fact(machine_fact("auto:blocker", "run-guards.ts"));
781        let confirmed_while_enabled = knowledge.facts[0].last_confirmed;
782
783        crate::test_env::set_var("LEAN_CTX_AUTO_CAPTURE", "0");
784        let refreshed = knowledge.add_fact(machine_fact("auto:blocker", "run-guards.ts"));
785        crate::test_env::remove_var("LEAN_CTX_AUTO_CAPTURE");
786
787        assert!(!refreshed);
788        assert_eq!(knowledge.facts.len(), 1);
789        assert_eq!(
790            knowledge.facts[0].last_confirmed, confirmed_while_enabled,
791            "a refused write must not refresh the existing fact"
792        );
793    }
794
795    #[test]
796    fn file_lock_is_exclusive_across_handles() {
797        // flock-style locks are tied to the open file description, so two
798        // independent `open()`s in the same process behave like two separate
799        // processes: while the first holds the exclusive lock, the second must
800        // fail to acquire it. This validates the cross-process guarantee that
801        // protects parallel CLI writes (issue #326).
802        let dir = tempfile::tempdir().unwrap();
803        let held = acquire_file_lock(dir.path()).expect("first lock must succeed");
804
805        let second = std::fs::OpenOptions::new()
806            .create(true)
807            .truncate(false)
808            .write(true)
809            .open(dir.path().join(".knowledge.lock"))
810            .unwrap();
811        assert!(
812            second.try_lock_exclusive().is_err(),
813            "a second handle must not acquire the lock while it is held"
814        );
815
816        drop(held);
817        // `close()` releases the flock synchronously, so the lock IS free here.
818        // Under heavy parallel test load, however, a single non-blocking
819        // `try_lock_exclusive()` can momentarily observe `EWOULDBLOCK` from
820        // scheduling jitter. A short bounded retry removes that flake without
821        // weakening the guarantee: the lock must become acquirable again.
822        let mut reacquired = false;
823        for _ in 0..50 {
824            if second.try_lock_exclusive().is_ok() {
825                reacquired = true;
826                break;
827            }
828            std::thread::sleep(std::time::Duration::from_millis(10));
829        }
830        assert!(
831            reacquired,
832            "lock must be acquirable within 500ms of release"
833        );
834    }
835
836    #[test]
837    fn write_json_atomic_leaves_valid_file_and_no_temp() {
838        let dir = tempfile::tempdir().unwrap();
839        let path = dir.path().join("knowledge.json");
840        write_json_atomic(dir.path(), &path, "{\"ok\":true}").unwrap();
841        assert_eq!(std::fs::read_to_string(&path).unwrap(), "{\"ok\":true}");
842        let leftover = std::fs::read_dir(dir.path())
843            .unwrap()
844            .filter_map(Result::ok)
845            .any(|e| e.file_name().to_string_lossy().contains(".tmp."));
846        assert!(!leftover, "no temp file should remain");
847    }
848
849    #[test]
850    fn load_rebuilds_ephemeral_index_without_changing_json() {
851        let _isolated = crate::core::data_dir::isolated_data_dir();
852        let project = tempfile::tempdir().unwrap();
853        let root = project.path().to_str().unwrap();
854        let policy = MemoryPolicy::default();
855        let mut knowledge = ProjectKnowledge::new(root);
856        knowledge.remember(
857            "architecture",
858            "database",
859            "PostgreSQL",
860            "test",
861            0.9,
862            &policy,
863        );
864        knowledge.save().unwrap();
865
866        let loaded = ProjectKnowledge::load(root).expect("saved knowledge should load");
867        assert!(loaded.index.token_positions.contains_key("postgresql"));
868        assert_eq!(loaded.recall("postgresql").len(), 1);
869
870        let json = serde_json::to_string(&loaded).unwrap();
871        assert!(!json.contains("\"index\""));
872    }
873}