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/// How long a knowledge write waits for the project's in-process and file
17/// locks. Bounded, so a stuck holder cannot hang a tool call; long enough that
18/// parallel `remember` calls on a loaded machine queue instead of failing,
19/// which would lose the fact #326 is about (2 s did not hold on a busy CI
20/// runner with seven writers).
21const KNOWLEDGE_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(10);
22
23/// Per-project-hash mutex registry. Serializes the read-modify-write cycle of
24/// `mutate_locked` so concurrent `remember` calls within a single process (e.g.
25/// parallel MCP tool calls) cannot clobber each other (issue #326). The outer
26/// map lock is held only briefly to clone the inner `Arc`; the inner lock is
27/// held across the load → mutate → save cycle.
28fn knowledge_lock(project_hash: &str) -> Arc<Mutex<()>> {
29    static KNOWLEDGE_LOCKS: OnceLock<Mutex<HashMap<String, Arc<Mutex<()>>>>> = OnceLock::new();
30    let map = KNOWLEDGE_LOCKS.get_or_init(|| Mutex::new(HashMap::new()));
31    let mut guard = map
32        .lock()
33        .unwrap_or_else(std::sync::PoisonError::into_inner);
34    guard
35        .entry(project_hash.to_string())
36        .or_insert_with(|| Arc::new(Mutex::new(())))
37        .clone()
38}
39
40/// Acquires an exclusive, cross-process advisory lock for a project's
41/// knowledge store. The returned file handle holds the lock until it is
42/// dropped; the OS releases it automatically if the process exits (even on
43/// crash), so there are no stale locks. This serializes the read-modify-write
44/// cycle across *separate processes* (parallel CLI invocations, CLI + daemon +
45/// MCP server), complementing the in-process mutex (issue #326).
46#[cfg(feature = "embeddings")]
47fn acquire_file_lock(dir: &Path) -> Option<std::fs::File> {
48    use fs2::FileExt;
49    let lock_path = dir.join(".knowledge.lock");
50    let file = std::fs::OpenOptions::new()
51        .create(true)
52        .truncate(false)
53        .write(true)
54        .open(&lock_path)
55        .ok()?;
56    #[cfg(unix)]
57    {
58        use std::os::unix::fs::PermissionsExt;
59        let _ = std::fs::set_permissions(&lock_path, std::fs::Permissions::from_mode(0o600));
60    }
61    // Blocks until every other process holding the lock releases it. A failure
62    // here (unsupported FS, etc.) degrades to the in-process lock only.
63    file.lock_exclusive().ok()?;
64    Some(file)
65}
66
67/// Atomically writes `json` to `path` by writing to a unique temp file in the
68/// same directory and renaming it into place. `rename` is atomic on every
69/// supported platform (and replaces the target on Windows), so readers and
70/// concurrent writers never observe a half-written file — preventing the
71/// trailing-garbage JSON corruption reported in issue #326. The temp file and
72/// the directory are synced, so a published store also survives a crash.
73fn write_json_atomic(path: &Path, json: &str) -> Result<(), String> {
74    #[cfg(unix)]
75    let owner_only: Option<std::fs::Permissions> =
76        Some(std::os::unix::fs::PermissionsExt::from_mode(0o600));
77    #[cfg(not(unix))]
78    let owner_only: Option<std::fs::Permissions> = None;
79    crate::core::atomic_fs::try_atomic_write(path, json.as_bytes(), owner_only.as_ref())
80        .map_err(|_| "knowledge publication failed".to_string())
81}
82
83/// Parsed stores, reused while their file is unchanged. Every tool call loads
84/// the store and parsing a large one is the whole cost (knowledge grows
85/// without limit, owner decision 24.10.). The key is length, modification
86/// time and inode: an atomic write replaces the file, so the inode alone
87/// already tells a rewrite apart. Each caller gets its own copy; views,
88/// admission and the project check still run on every load.
89fn parse_store_cached(path: &Path) -> Result<ProjectKnowledge, &'static str> {
90    type Key = (u64, Option<std::time::SystemTime>, u64);
91    static PARSED: OnceLock<Mutex<HashMap<PathBuf, (Key, ProjectKnowledge)>>> = OnceLock::new();
92    const KEPT: usize = 8;
93
94    let metadata =
95        std::fs::symlink_metadata(path).map_err(|_| "knowledge input metadata unavailable")?;
96    if !metadata.is_file() {
97        return Err("knowledge input is unavailable or uninspectable");
98    }
99    #[cfg(unix)]
100    let inode = std::os::unix::fs::MetadataExt::ino(&metadata);
101    #[cfg(not(unix))]
102    let inode = 0;
103    let key: Key = (metadata.len(), metadata.modified().ok(), inode);
104    let cache = PARSED.get_or_init(Mutex::default);
105    if let Some((cached_key, knowledge)) = cache
106        .lock()
107        .unwrap_or_else(std::sync::PoisonError::into_inner)
108        .get(path)
109        && *cached_key == key
110    {
111        return Ok(knowledge.clone());
112    }
113    let text = crate::core::policy::diagnostics::Target::read_store_file(path)
114        .ok_or("knowledge input is unavailable or uninspectable")?;
115    let knowledge: ProjectKnowledge =
116        serde_json::from_str(&text).map_err(|_| "knowledge input is invalid")?;
117    let mut parsed = cache
118        .lock()
119        .unwrap_or_else(std::sync::PoisonError::into_inner);
120    if parsed.len() >= KEPT && !parsed.contains_key(path) {
121        parsed.clear();
122    }
123    parsed.insert(path.to_path_buf(), (key, knowledge.clone()));
124    Ok(knowledge)
125}
126
127/// Whether every record of a serialized store passes the policy unchanged.
128/// Records are inspected one at a time: the inspector refuses any value over
129/// the protected-content cap, and the store as a whole outgrows it (owner
130/// decision 24.10.: no knowledge limits).
131fn store_is_policy_safe(
132    store: &serde_json::Value,
133    policy: &crate::core::policy::runtime::ActivePolicy,
134) -> bool {
135    let unchanged = |value: &serde_json::Value| {
136        crate::core::policy::diagnostics::inspect(value, Some(policy)).as_ref() == Some(value)
137    };
138    match store {
139        serde_json::Value::Object(fields) => fields.values().all(|field| match field {
140            serde_json::Value::Array(records) => records.iter().all(unchanged),
141            other => unchanged(other),
142        }),
143        other => unchanged(other),
144    }
145}
146
147/// Marker that identifies a fact as machine-derived rather than curated.
148///
149/// Both automatic producers already carry it: `extract_session_facts` tags the
150/// *category* (`auto:decision`, `auto:pattern`, `auto:blocker`) and
151/// `auto_capture` derives an `auto:`-prefixed *key*. Nothing a person writes
152/// through `ctx_knowledge(action="remember")` does.
153pub(crate) const MACHINE_DERIVED_PREFIX: &str = "auto:";
154
155/// Whether this fact was derived by lean-ctx rather than written by a person.
156pub(crate) fn is_machine_derived(category: &str, key: &str) -> bool {
157    category.trim_start().starts_with(MACHINE_DERIVED_PREFIX)
158        || key.trim_start().starts_with(MACHINE_DERIVED_PREFIX)
159}
160
161/// Whether a machine-derived fact may enter the durable store right now.
162///
163/// #1802: `auto_capture = false` was honoured by exactly one producer
164/// (`auto_capture::capture_finding`) and ignored by the other
165/// (`extract_session_facts`, reached from both the consolidation engine and
166/// the session *save* path) — so a single MCP call re-materialised every
167/// deleted `auto:*` fact, complete with its original `created_at`, and a
168/// curated store could not be kept clean.
169///
170/// The gate therefore lives here, at the store's own ingestion points, and not
171/// at the producers: a check placed at a call site only covers the call sites
172/// that exist when it is written, which is exactly how this defect arose.
173/// Session state itself is left untouched — it is ephemeral, capacity-capped,
174/// and backs handoff, session recap and metrics, none of which this key
175/// disables.
176pub(crate) fn machine_derived_writes_allowed() -> bool {
177    crate::core::auto_capture::is_enabled()
178}
179
180impl ProjectKnowledge {
181    /// Return the most recent active decision-like facts for session handoff.
182    /// Adds a pre-built fact, coalescing repeated observations into confirmations.
183    pub fn add_fact(&mut self, mut fact: KnowledgeFact) -> bool {
184        let trimmed_cat = fact.category.trim().to_string();
185        fact.category = trimmed_cat;
186        let trimmed_val = fact.value.trim().to_string();
187        fact.value = trimmed_val;
188        if fact.category.is_empty() || fact.value.is_empty() {
189            return false;
190        }
191        // #1802: refuse machine-derived facts while auto-capture is off. Placed
192        // before the coalescing branch below so a disabled run cannot even
193        // refresh `last_confirmed` on facts a previous enabled run left behind.
194        if is_machine_derived(&fact.category, &fact.key) && !machine_derived_writes_allowed() {
195            return false;
196        }
197        // Same store boundary as `remember_with_origin` (G5, E3).
198        let Some([category, key, value]) = super::core::admit_fact_fields(
199            &self.project_root,
200            [&fact.category, &fact.key, &fact.value],
201        ) else {
202            return false;
203        };
204        (fact.category, fact.key, fact.value) = (category, key, value);
205
206        if let Some(existing) = self.facts.iter_mut().find(|existing| {
207            existing.category == fact.category
208                && existing.value == fact.value
209                && existing.origin == fact.origin
210        }) {
211            if fact.last_confirmed > existing.last_confirmed {
212                existing.last_confirmed = fact.last_confirmed;
213            }
214            existing.confidence = existing.confidence.max(fact.confidence);
215            existing.confirmation_count = existing.confirmation_count.saturating_add(1);
216            existing.update_fidelity();
217        } else {
218            fact.update_fidelity();
219            self.facts.push(fact);
220            self.rebuild_index();
221        }
222
223        self.updated_at = Utc::now();
224        true
225    }
226
227    pub fn recent_decisions(&self, limit: usize) -> Vec<KnowledgeFact> {
228        let mut decisions: Vec<KnowledgeFact> = self
229            .facts
230            .iter()
231            .filter(|fact| {
232                let category = fact.category.to_ascii_lowercase();
233                fact.is_current()
234                    && (category.contains("decision")
235                        || category.contains("architecture")
236                        || category.contains("solution"))
237            })
238            .cloned()
239            .collect();
240        decisions.sort_by(|a, b| {
241            b.last_confirmed
242                .cmp(&a.last_confirmed)
243                .then_with(|| b.created_at.cmp(&a.created_at))
244        });
245        decisions.truncate(limit);
246        decisions
247    }
248    /// Keyword-based knowledge search across all facts.
249    /// Serves as the API surface for semantic retrieval; currently falls back
250    /// to substring matching. When the embedding model is loaded, this will
251    /// use HNSW vector search instead.
252    pub fn search_semantic(&self, query: &str, limit: usize) -> Vec<KnowledgeFact> {
253        let query_lower = query.to_lowercase();
254        let terms: Vec<&str> = query_lower.split_whitespace().collect();
255        if terms.is_empty() {
256            return Vec::new();
257        }
258        let mut scored: Vec<(usize, &KnowledgeFact)> = self
259            .facts
260            .iter()
261            .filter(|f| f.valid_until.is_none_or(|t| t > chrono::Utc::now()))
262            .map(|fact| {
263                let haystack = format!(
264                    "{} {} {}",
265                    fact.category.to_lowercase(),
266                    fact.value.to_lowercase(),
267                    fact.key.to_lowercase(),
268                );
269                let score = terms.iter().filter(|t| haystack.contains(*t)).count();
270                (score, fact)
271            })
272            .filter(|(score, _)| *score > 0)
273            .collect();
274        scored.sort_by_key(|a| std::cmp::Reverse(a.0));
275        scored
276            .into_iter()
277            .take(limit)
278            .map(|(_, f)| f.clone())
279            .collect()
280    }
281
282    pub fn list_project_roots() -> Result<Vec<String>, String> {
283        let base = crate::core::data_dir::lean_ctx_data_dir()?.join("knowledge");
284        if !base.exists() {
285            return Ok(Vec::new());
286        }
287
288        let mut roots = Vec::new();
289        let mut seen = HashSet::new();
290        let entries = std::fs::read_dir(&base).map_err(|e| e.to_string())?;
291        for entry in entries.flatten() {
292            let path = entry.path().join("knowledge.json");
293            if !path.is_file() {
294                continue;
295            }
296            let Ok(content) = std::fs::read_to_string(&path) else {
297                continue;
298            };
299            let Ok(knowledge) = serde_json::from_str::<Self>(&content) else {
300                continue;
301            };
302            if seen.insert(knowledge.project_root.clone()) {
303                roots.push(knowledge.project_root);
304            }
305        }
306
307        roots.sort();
308        Ok(roots)
309    }
310
311    /// Load one admitted, non-migrating read view for an export operation.
312    /// Hidden rows are omitted from the view and never rewrite the durable store.
313    pub(crate) fn load_for_admission(
314        project_root: &str,
315        admission: &super::protection::KnowledgeAdmission,
316    ) -> Result<Option<Self>, String> {
317        let hash = hash_project_root(project_root);
318        let path = knowledge_dir(&hash)?.join("knowledge.json");
319        match std::fs::symlink_metadata(&path) {
320            Ok(metadata) if metadata.is_file() => {}
321            Ok(_) => return Err("knowledge store is not a regular file".into()),
322            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
323                // Still reject a pending legacy migration instead of silently
324                // exporting an empty view that hides the existing store.
325                let _ = Self::load_for_checked_capture(project_root)?;
326                admission.authorize_gateway()?;
327                return Ok(None);
328            }
329            Err(_) => return Err("knowledge store metadata unavailable".into()),
330        }
331        let raw = Self::load_for_checked_capture(project_root)?;
332        let view = admission.view(&raw)?.admit_sources();
333        admission.authorize_gateway()?;
334        Ok(Some(view))
335    }
336
337    /// Optional capture must not trigger legacy migration writes during a read,
338    /// or replace an unreadable existing store with a newly created empty one.
339    pub(crate) fn load_for_checked_capture(project_root: &str) -> Result<Self, String> {
340        let hash = hash_project_root(project_root);
341        let path = knowledge_dir(&hash)?.join("knowledge.json");
342        match std::fs::symlink_metadata(&path) {
343            Ok(_) => {
344                let mut knowledge = parse_store_cached(&path)?;
345                let canonical = |root: &str| {
346                    crate::core::pathutil::safe_canonicalize_bounded(Path::new(root), 2000)
347                };
348                // The recorded root is the authority. The hash is derived: a
349                // store copied in from an earlier hash of the same project
350                // (path normalization, an identity change) still names it.
351                if canonical(&knowledge.project_root) != canonical(project_root) {
352                    return Err("knowledge input belongs to a different project".into());
353                }
354                knowledge.project_hash = hash;
355                knowledge.rebuild_index();
356                return Ok(knowledge);
357            }
358            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
359            Err(_) => return Err("knowledge input metadata unavailable".into()),
360        }
361        let mut legacy = crate::core::project_hash::legacy_unnormalized_hashes(project_root);
362        legacy.push(crate::core::project_hash::hash_path_only(project_root));
363        for old_hash in legacy.into_iter().filter(|old| old != &hash) {
364            match std::fs::symlink_metadata(knowledge_dir(&old_hash)?.join("knowledge.json")) {
365                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
366                _ => return Err("knowledge requires an explicit legacy migration".into()),
367            }
368        }
369        Ok(Self::new(project_root))
370    }
371
372    pub(crate) fn save_policy_checked(
373        &self,
374        source_tool: &str,
375        original_content: &str,
376    ) -> Result<(), String> {
377        if let Some(policy) =
378            crate::core::policy::runtime::for_project(Path::new(&self.project_root))?
379        {
380            if !policy.tool_allowed("ctx_knowledge")
381                || !policy.tool_allowed(source_tool)
382                || crate::core::policy::content::evaluate_text(original_content, &policy).blocked
383            {
384                return Err("knowledge persistence withheld by policy".into());
385            }
386            let original =
387                serde_json::to_value(self).map_err(|_| "knowledge is not inspectable")?;
388            if !store_is_policy_safe(&original, &policy) {
389                // Preserve structural identity and old customer data. Writers
390                // must supply already-safe facts; never silently rewrite keys
391                // or republish an unsafe legacy store into a temporary file.
392                return Err("knowledge persistence requires policy-safe fields".into());
393            }
394        }
395        // The capture caller already holds this project's checked write lock.
396        self.save_unlocked()
397    }
398
399    pub fn save(&self) -> Result<(), String> {
400        let admission = super::protection::KnowledgeAdmission::capture(&self.project_root)?;
401        if Path::new(&self.project_root).is_dir() {
402            crate::core::policy::runtime::with_explicit_project_source_view(
403                Path::new(&self.project_root),
404                |authority| {
405                    Self::with_project_lock_checked(&self.project_root, || {
406                        admission.authorize_publication(authority)?;
407                        self.save_with_admission(&admission)
408                    })?
409                },
410            )?
411        } else {
412            if crate::core::policy::runtime::inherited_source_view().is_some() {
413                return Err("knowledge project root unavailable".into());
414            }
415            Self::with_project_lock_checked(&self.project_root, || {
416                self.save_with_admission(&admission)
417            })?
418        }
419    }
420
421    fn save_unlocked(&self) -> Result<(), String> {
422        let admission = super::protection::KnowledgeAdmission::capture(&self.project_root)?;
423        self.save_with_admission(&admission)
424    }
425
426    fn save_with_admission(
427        &self,
428        admission: &super::protection::KnowledgeAdmission,
429    ) -> Result<(), String> {
430        let candidate = if self.withheld.is_empty() {
431            self.clone()
432        } else {
433            let existing = Self::load_for_checked_capture(&self.project_root)?;
434            self.complete_for_storage(&existing)?
435        };
436        candidate.save_complete_with_admission(admission)
437    }
438
439    fn save_complete_with_admission(
440        &self,
441        admission: &super::protection::KnowledgeAdmission,
442    ) -> Result<(), String> {
443        if self.project_hash != hash_project_root(&self.project_root) {
444            return Err("knowledge storage identity mismatch".into());
445        }
446        let existing = Self::load_for_checked_capture(&self.project_root)?;
447        admission.require_safe(&existing)?;
448        admission.require_safe(self)?;
449
450        let dir = knowledge_dir(&self.project_hash)?;
451        std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
452        #[cfg(unix)]
453        {
454            use std::os::unix::fs::PermissionsExt;
455            let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
456        }
457
458        let path = dir.join("knowledge.json");
459        let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
460        admission.authorize_gateway()?;
461        write_json_atomic(&path, &json)?;
462        Ok(())
463    }
464
465    /// Runs `f` while holding this project's locks — the in-process per-hash
466    /// mutex *and* the cross-process advisory file lock — without loading or
467    /// saving the knowledge JSON itself. [`mutate_locked`](Self::mutate_locked)
468    /// is built on this, and side-car stores that must stay consistent with the
469    /// facts (today: the embedding index) call it directly so their
470    /// read-modify-write is serialized against parallel
471    /// `remember`/`remove`/`reindex`. That side-car write used to run lock-free,
472    /// so concurrent callers clobbered each other's embeddings and pruned
473    /// just-stored vectors, degrading semantic recall (issue #412, a #326
474    /// follow-up).
475    #[cfg(feature = "embeddings")]
476    pub(crate) fn with_project_lock<T>(project_root: &str, f: impl FnOnce() -> T) -> T {
477        let hash = hash_project_root(project_root);
478        let lock = knowledge_lock(&hash);
479        let _guard = lock
480            .lock()
481            .unwrap_or_else(std::sync::PoisonError::into_inner);
482
483        // Cross-process lock: create the dir up front so the lock file has a
484        // home, then block until any other process releases it. Held for the
485        // whole critical section via `_file_lock`'s lifetime.
486        let _file_lock = match knowledge_dir(&hash) {
487            Ok(dir) => {
488                let _ = std::fs::create_dir_all(&dir);
489                acquire_file_lock(&dir)
490            }
491            Err(_) => None,
492        };
493
494        f()
495    }
496
497    /// Runs a read-modify-write cycle under `with_project_lock`, then saves
498    /// atomically. The knowledge is (re)loaded *inside* the lock so
499    /// the closure always operates on the latest on-disk state; this is what
500    /// prevents lost updates when several `remember` calls run in parallel —
501    /// whether as threads in one process (parallel MCP calls) or as separate
502    /// processes (parallel CLI invocations, CLI + daemon + MCP server) — see
503    /// issue #326. Returns the persisted knowledge plus the closure's return
504    /// value so the caller can build a response from the committed state.
505    pub(crate) fn with_project_lock_checked<T>(
506        project_root: &str,
507        f: impl FnOnce() -> T,
508    ) -> Result<T, String> {
509        use fs2::FileExt;
510        let hash = hash_project_root(project_root);
511        let lock = knowledge_lock(&hash);
512        let deadline = std::time::Instant::now() + KNOWLEDGE_LOCK_WAIT;
513        let _guard = loop {
514            match lock.try_lock() {
515                Ok(guard) => break guard,
516                Err(std::sync::TryLockError::WouldBlock)
517                    if std::time::Instant::now() < deadline =>
518                {
519                    std::thread::sleep(std::time::Duration::from_millis(5));
520                }
521                Err(_) => return Err("knowledge lock unavailable".into()),
522            }
523        };
524        let dir = knowledge_dir(&hash)?;
525        std::fs::create_dir_all(&dir).map_err(|_| "knowledge directory unavailable")?;
526        let file = crate::core::policy::diagnostics::open_append(&dir.join(".knowledge.lock"))
527            .map_err(|_| "knowledge file lock unavailable")?;
528        loop {
529            match file.try_lock_exclusive() {
530                Ok(()) => break,
531                Err(e)
532                    if crate::core::file_lock::is_contended(&e)
533                        && std::time::Instant::now() < deadline =>
534                {
535                    std::thread::sleep(std::time::Duration::from_millis(5));
536                }
537                Err(_) => return Err("knowledge file lock unavailable".into()),
538            }
539        }
540        let output = f();
541        let _ = FileExt::unlock(&file);
542        Ok(output)
543    }
544
545    pub fn mutate_locked<T>(
546        project_root: &str,
547        f: impl FnOnce(&mut Self) -> T,
548    ) -> Result<(Self, T), String> {
549        let admission = super::protection::KnowledgeAdmission::capture(project_root)?;
550        Self::mutate_locked_with_admission(project_root, &admission, f)
551    }
552
553    pub(crate) fn mutate_locked_with_admission<T>(
554        project_root: &str,
555        admission: &super::protection::KnowledgeAdmission,
556        f: impl FnOnce(&mut Self) -> T,
557    ) -> Result<(Self, T), String> {
558        crate::core::providers::provenance::with_reuse_deadline(|| {
559            Self::mutate_locked_in_scope(project_root, admission, f)
560        })
561    }
562
563    fn mutate_locked_in_scope<T>(
564        project_root: &str,
565        admission: &super::protection::KnowledgeAdmission,
566        f: impl FnOnce(&mut Self) -> T,
567    ) -> Result<(Self, T), String> {
568        if Path::new(project_root).is_dir() {
569            crate::core::policy::runtime::with_explicit_project_source_view(
570                Path::new(project_root),
571                |authority| Self::mutate_locked_scoped(project_root, admission, Some(authority), f),
572            )?
573        } else {
574            if crate::core::policy::runtime::inherited_source_view().is_some() {
575                return Err("knowledge project root unavailable".into());
576            }
577            if let Some(request) = crate::core::policy::diagnostics::request_project()
578                && crate::core::pathutil::safe_canonicalize_bounded(&request, 2000)
579                    != crate::core::pathutil::safe_canonicalize_bounded(
580                        Path::new(project_root),
581                        2000,
582                    )
583            {
584                return Err("knowledge project does not match protected request".into());
585            }
586            Self::mutate_locked_scoped(project_root, admission, None, f)
587        }
588    }
589
590    fn mutate_locked_scoped<T>(
591        project_root: &str,
592        admission: &super::protection::KnowledgeAdmission,
593        authority: Option<&crate::core::policy::runtime::PublicationAuthority>,
594        f: impl FnOnce(&mut Self) -> T,
595    ) -> Result<(Self, T), String> {
596        Self::with_project_lock_checked(project_root, || {
597            // An identity change moved this project's hash: its store under
598            // the earlier hash (proven by the recorded root) is copied over
599            // first, so a write never forks the project's knowledge.
600            let current = knowledge_dir(&hash_project_root(project_root))?.join("knowledge.json");
601            if !current.exists()
602                && let Some(old) =
603                    crate::core::legacy_adoption::drifted_knowledge_partition(project_root)
604            {
605                crate::core::legacy_adoption::copy_knowledge_partition(&old, project_root)?;
606            }
607            let raw = Self::load_for_checked_capture(project_root)?;
608            admission.require_safe(&raw)?;
609            let mut knowledge = raw.admit_sources();
610            let out = f(&mut knowledge);
611            admission.require_safe(&knowledge)?;
612            admission.authorize_gateway()?;
613            if let Some(authority) = authority {
614                authority.verify()?;
615            }
616            knowledge.save_with_admission(admission)?;
617            Ok((knowledge.admit_sources(), out))
618        })?
619    }
620
621    pub fn load(project_root: &str) -> Option<Self> {
622        let admission = super::protection::KnowledgeAdmission::capture(project_root).ok()?;
623        let legacy_source_safe = |legacy_hash: &str| {
624            let Ok(path) = knowledge_dir(legacy_hash) else {
625                return false;
626            };
627            let path = path.join("knowledge.json");
628            match std::fs::symlink_metadata(&path) {
629                Err(error) if error.kind() == std::io::ErrorKind::NotFound => true,
630                Err(_) => false,
631                Ok(_) => {
632                    let Some(content) =
633                        crate::core::policy::diagnostics::Target::read_store_file(&path)
634                    else {
635                        return false;
636                    };
637                    let Ok(legacy) = serde_json::from_str::<Self>(&content) else {
638                        return false;
639                    };
640                    crate::core::pathutil::safe_canonicalize_bounded(
641                        Path::new(&legacy.project_root),
642                        2000,
643                    ) == crate::core::pathutil::safe_canonicalize_bounded(
644                        Path::new(project_root),
645                        2000,
646                    ) && admission.require_safe(&legacy).is_ok()
647                }
648            }
649        };
650        match super::protection::current(project_root) {
651            Ok(Some(_)) => {
652                let path = knowledge_dir(&hash_project_root(project_root))
653                    .ok()?
654                    .join("knowledge.json");
655                std::fs::symlink_metadata(path).ok()?;
656                let raw = Self::load_for_checked_capture(project_root).ok()?;
657                return admission.view(&raw).ok().map(Self::admit_sources);
658            }
659            Err(_) => return None,
660            Ok(None) => {}
661        }
662        let hash = hash_project_root(project_root);
663        let dir = knowledge_dir(&hash).ok()?;
664        let path = dir.join("knowledge.json");
665
666        if let Ok(mut k) = parse_store_cached(&path) {
667            // The recorded root is the authority; the hash is derived
668            // and is re-keyed for a store copied from an earlier hash.
669            if crate::core::pathutil::safe_canonicalize_bounded(Path::new(&k.project_root), 2000)
670                != crate::core::pathutil::safe_canonicalize_bounded(Path::new(project_root), 2000)
671            {
672                return None;
673            }
674            k.project_hash = hash;
675            k.rebuild_index();
676            return admission.view(&k).ok().map(Self::admit_sources);
677        }
678
679        let old_hash = crate::core::project_hash::hash_path_only(project_root);
680        if old_hash != hash {
681            if !legacy_source_safe(&old_hash) || admission.authorize_gateway().is_err() {
682                return None;
683            }
684            crate::core::project_hash::migrate_if_needed(&old_hash, &hash, project_root);
685            if let Ok(content) = std::fs::read_to_string(&path)
686                && let Ok(mut k) = serde_json::from_str::<Self>(&content)
687            {
688                k.project_hash = hash;
689                k.rebuild_index();
690                if admission.require_safe(&k).is_err()
691                    || admission.authorize_gateway().is_err()
692                    || k.save_with_admission(&admission).is_err()
693                {
694                    return None;
695                }
696                return admission.view(&k).ok().map(Self::admit_sources);
697            }
698        }
699
700        // Migrate stores created before path normalization (issue #325): on
701        // Windows the CLI keyed its store by a backslash path, splitting it from
702        // the forward-slash MCP store. Pull any such legacy store into the
703        // canonical (normalized) location so facts converge.
704        for legacy_hash in crate::core::project_hash::legacy_unnormalized_hashes(project_root) {
705            if legacy_hash == hash {
706                continue;
707            }
708            if !legacy_source_safe(&legacy_hash) || admission.authorize_gateway().is_err() {
709                return None;
710            }
711            crate::core::project_hash::migrate_if_needed(&legacy_hash, &hash, project_root);
712            if let Ok(content) = std::fs::read_to_string(&path)
713                && let Ok(mut k) = serde_json::from_str::<Self>(&content)
714            {
715                k.project_hash = hash;
716                k.rebuild_index();
717                if admission.require_safe(&k).is_err()
718                    || admission.authorize_gateway().is_err()
719                    || k.save_with_admission(&admission).is_err()
720                {
721                    return None;
722                }
723                return admission.view(&k).ok().map(Self::admit_sources);
724            }
725        }
726
727        // The project's identity (git remote, package name, `.lean-ctx-id`)
728        // changed, so its hash moved: a store whose recorded root is this
729        // path is the project's own. Its files are copied (never moved) into
730        // the current partition and pass the same guards as above.
731        if let Some(old_hash) =
732            crate::core::legacy_adoption::drifted_knowledge_partition(project_root)
733        {
734            if !legacy_source_safe(&old_hash) || admission.authorize_gateway().is_err() {
735                return None;
736            }
737            crate::core::legacy_adoption::copy_knowledge_partition(&old_hash, project_root).ok()?;
738            if let Ok(content) = std::fs::read_to_string(&path)
739                && let Ok(mut k) = serde_json::from_str::<Self>(&content)
740                && crate::core::pathutil::safe_canonicalize_bounded(
741                    Path::new(&k.project_root),
742                    2000,
743                ) == crate::core::pathutil::safe_canonicalize_bounded(
744                    Path::new(project_root),
745                    2000,
746                )
747            {
748                k.project_hash = hash;
749                k.rebuild_index();
750                if admission.require_safe(&k).is_err()
751                    || admission.authorize_gateway().is_err()
752                    || k.save_with_admission(&admission).is_err()
753                {
754                    return None;
755                }
756                return admission.view(&k).ok().map(Self::admit_sources);
757            }
758        }
759
760        None
761    }
762
763    pub fn load_or_create(project_root: &str) -> Self {
764        Self::load(project_root).unwrap_or_else(|| Self::new(project_root))
765    }
766
767    /// Migrates legacy knowledge that was accidentally stored under an empty project_root ("")
768    /// into the given `target_root`. Keeps a timestamped backup of the legacy file.
769    pub fn migrate_legacy_empty_root(
770        target_root: &str,
771        policy: &MemoryPolicy,
772    ) -> Result<bool, String> {
773        if target_root.trim().is_empty() {
774            return Ok(false);
775        }
776
777        if super::protection::current(target_root)?.is_some() {
778            return Err("unscoped legacy knowledge requires explicit protected migration".into());
779        }
780        // This explicit compatibility migration may read the old empty-root
781        // store, but general load/save must never treat an empty root as authority.
782        let mut legacy_store = None;
783        for hash in [
784            hash_project_root(""),
785            crate::core::project_hash::hash_path_only(""),
786        ] {
787            let path = knowledge_dir(&hash)?.join("knowledge.json");
788            match std::fs::symlink_metadata(&path) {
789                Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
790                Err(_) => return Err("legacy knowledge input unavailable".into()),
791                Ok(_) => {}
792            }
793            let text = crate::core::policy::diagnostics::Target::read_store_file(&path)
794                .ok_or("legacy knowledge input is uninspectable")?;
795            let legacy: Self =
796                serde_json::from_str(&text).map_err(|_| "invalid legacy knowledge")?;
797            legacy_store = Some((legacy, path));
798            break;
799        }
800        let Some((legacy, legacy_path)) = legacy_store else {
801            return Ok(false);
802        };
803
804        if !legacy.project_root.trim().is_empty() {
805            return Ok(false);
806        }
807        if legacy.facts.is_empty() && legacy.patterns.is_empty() && legacy.history.is_empty() {
808            return Ok(false);
809        }
810
811        Self::with_project_lock_checked(target_root, || {
812            if super::protection::current(target_root)?.is_some() {
813                return Err("legacy migration withheld by changed project policy".into());
814            }
815            let mut target = Self::load_or_create(target_root);
816
817            fn fact_key(f: &KnowledgeFact) -> String {
818                format!(
819                    "{}|{}|{}|{}|{}",
820                    f.category, f.key, f.value, f.source_session, f.created_at
821                )
822            }
823            fn pattern_key(p: &ProjectPattern) -> String {
824                format!(
825                    "{}|{}|{}|{}",
826                    p.pattern_type, p.description, p.source_session, p.created_at
827                )
828            }
829            fn history_key(h: &ConsolidatedInsight) -> String {
830                format!(
831                    "{}|{}|{}",
832                    h.summary,
833                    h.from_sessions.join(","),
834                    h.timestamp
835                )
836            }
837
838            let mut seen_facts: std::collections::HashSet<String> =
839                target.facts.iter().map(fact_key).collect();
840            for f in legacy.facts {
841                if seen_facts.insert(fact_key(&f)) {
842                    target.facts.push(f);
843                }
844            }
845
846            let mut seen_patterns: std::collections::HashSet<String> =
847                target.patterns.iter().map(pattern_key).collect();
848            for p in legacy.patterns {
849                if seen_patterns.insert(pattern_key(&p)) {
850                    target.patterns.push(p);
851                }
852            }
853
854            let mut seen_history: std::collections::HashSet<String> =
855                target.history.iter().map(history_key).collect();
856            for h in legacy.history {
857                if seen_history.insert(history_key(&h)) {
858                    target.history.push(h);
859                }
860            }
861
862            target.facts.sort_by(|a, b| {
863                b.created_at
864                    .cmp(&a.created_at)
865                    .then_with(|| b.confidence.total_cmp(&a.confidence))
866            });
867            target
868                .patterns
869                .sort_by_key(|x| std::cmp::Reverse(x.created_at));
870            if target.patterns.len() > policy.knowledge.max_patterns {
871                target.patterns.truncate(policy.knowledge.max_patterns);
872            }
873            target
874                .history
875                .sort_by_key(|x| std::cmp::Reverse(x.timestamp));
876            if target.history.len() > policy.knowledge.max_history {
877                target.history.truncate(policy.knowledge.max_history);
878            }
879
880            target.updated_at = Utc::now();
881            if super::protection::current(target_root)?.is_some() {
882                return Err("legacy migration withheld by changed project policy".into());
883            }
884            target.save_unlocked()?;
885
886            let legacy_dir = legacy_path.parent().ok_or("legacy directory unavailable")?;
887            if legacy_path.exists() {
888                let ts = Utc::now().format("%Y%m%d-%H%M%S");
889                let backup = legacy_dir.join(format!("knowledge.legacy-empty-root.{ts}.json"));
890                std::fs::hard_link(&legacy_path, &backup)
891                    .map_err(|_| "legacy backup could not be preserved")?;
892                std::fs::remove_file(&legacy_path)
893                    .map_err(|_| "legacy backup retained but source cleanup failed")?;
894            }
895
896            Ok(true)
897        })?
898    }
899}
900
901#[cfg(test)]
902mod tests {
903    use super::*;
904    use fs2::FileExt;
905
906    // --- #1802: `auto_capture = false` must hold at the store, not the callers ---
907
908    fn machine_fact(category: &str, key: &str) -> KnowledgeFact {
909        let now = chrono::Utc::now();
910        KnowledgeFact {
911            anchors: Vec::new(),
912            review: None,
913            capture: Default::default(),
914            origin: crate::core::knowledge::FactOrigin::Local,
915            category: category.to_string(),
916            key: key.to_string(),
917            value: "Finding: run-guards.ts: Read run-guards.ts (92L)".to_string(),
918            source_session: "session-1".to_string(),
919            confidence: 0.8,
920            created_at: now,
921            last_confirmed: now,
922            retrieval_count: 0,
923            last_retrieved: None,
924            valid_from: None,
925            valid_until: None,
926            supersedes: None,
927            confirmation_count: 1,
928            feedback_up: 0,
929            feedback_down: 0,
930            last_feedback: None,
931            privacy: Default::default(),
932            sensitivity: Default::default(),
933            imported_from: None,
934            archetype: Default::default(),
935            fidelity: None,
936            revision_count: 0,
937            status: None,
938            validity: None,
939        }
940    }
941
942    #[test]
943    fn machine_derived_is_recognised_in_either_ingestion_shape() {
944        // `extract_session_facts` marks the category; `auto_capture` marks the
945        // key. Both producers must be recognisable by one predicate.
946        assert!(is_machine_derived("auto:blocker", "run-guards.ts"));
947        assert!(is_machine_derived("blocker", "auto:config.rs"));
948        assert!(!is_machine_derived("konventionen", "naming"));
949        assert!(!is_machine_derived("ops", "deploy"));
950    }
951
952    #[test]
953    fn a_curated_fact_is_never_affected_by_the_gate() {
954        // The key disables *automatic* capture. A fact a person wrote must be
955        // storable whatever the flag says, or the feature would be a footgun.
956        // Isolated: the store boundary reads the data dir and the active
957        // policy, which concurrent tests change.
958        let _data = crate::core::data_dir::isolated_data_dir();
959        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
960        let knowledge_root = tempfile::tempdir().unwrap();
961        let mut knowledge = ProjectKnowledge::new(knowledge_root.path().to_str().unwrap());
962        assert!(
963            knowledge.add_fact(machine_fact("konventionen", "naming")),
964            "curated facts must always be accepted"
965        );
966    }
967
968    #[test]
969    fn disabled_capture_blocks_every_machine_derived_shape() {
970        // The regression: a single MCP call re-materialised deleted `auto:*`
971        // facts because only one of two producers consulted the flag. Asserting
972        // at the store covers both, and any producer added later.
973        let _env = crate::core::data_dir::test_env_lock();
974        crate::test_env::set_var("LEAN_CTX_AUTO_CAPTURE", "0");
975
976        let knowledge_root = tempfile::tempdir().unwrap();
977
978        let mut knowledge = ProjectKnowledge::new(knowledge_root.path().to_str().unwrap());
979        let category_marked = knowledge.add_fact(machine_fact("auto:blocker", "run-guards.ts"));
980        let key_marked = knowledge.add_fact(machine_fact("blocker", "auto:config.rs"));
981
982        crate::test_env::remove_var("LEAN_CTX_AUTO_CAPTURE");
983
984        assert!(!category_marked, "auto:* category must be refused");
985        assert!(!key_marked, "auto:* key must be refused");
986        assert!(
987            knowledge.facts.is_empty(),
988            "nothing machine-derived may reach the durable store"
989        );
990    }
991
992    #[test]
993    fn enabled_capture_still_stores_machine_derived_facts() {
994        let _env = crate::core::data_dir::test_env_lock();
995        crate::test_env::set_var("LEAN_CTX_AUTO_CAPTURE", "1");
996
997        let knowledge_root = tempfile::tempdir().unwrap();
998
999        let mut knowledge = ProjectKnowledge::new(knowledge_root.path().to_str().unwrap());
1000        let stored = knowledge.add_fact(machine_fact("auto:blocker", "run-guards.ts"));
1001
1002        crate::test_env::remove_var("LEAN_CTX_AUTO_CAPTURE");
1003
1004        assert!(stored, "the default behaviour must be unchanged");
1005    }
1006
1007    #[test]
1008    fn disabled_capture_does_not_refresh_existing_machine_facts() {
1009        // Facts from an earlier enabled run stay on disk — the fix stops new
1010        // writes, it does not delete history. But a disabled run must not keep
1011        // touching them either, or they would look perpetually fresh to the
1012        // lifecycle and never age out.
1013        let _env = crate::core::data_dir::test_env_lock();
1014        crate::test_env::set_var("LEAN_CTX_AUTO_CAPTURE", "1");
1015        let knowledge_root = tempfile::tempdir().unwrap();
1016        let mut knowledge = ProjectKnowledge::new(knowledge_root.path().to_str().unwrap());
1017        knowledge.add_fact(machine_fact("auto:blocker", "run-guards.ts"));
1018        let confirmed_while_enabled = knowledge.facts[0].last_confirmed;
1019
1020        crate::test_env::set_var("LEAN_CTX_AUTO_CAPTURE", "0");
1021        let refreshed = knowledge.add_fact(machine_fact("auto:blocker", "run-guards.ts"));
1022        crate::test_env::remove_var("LEAN_CTX_AUTO_CAPTURE");
1023
1024        assert!(!refreshed);
1025        assert_eq!(knowledge.facts.len(), 1);
1026        assert_eq!(
1027            knowledge.facts[0].last_confirmed, confirmed_while_enabled,
1028            "a refused write must not refresh the existing fact"
1029        );
1030    }
1031
1032    #[test]
1033    fn file_lock_is_exclusive_across_handles() {
1034        // flock-style locks are tied to the open file description, so two
1035        // independent `open()`s in the same process behave like two separate
1036        // processes: while the first holds the exclusive lock, the second must
1037        // fail to acquire it. This validates the cross-process guarantee that
1038        // protects parallel CLI writes (issue #326).
1039        let dir = tempfile::tempdir().unwrap();
1040        let held = acquire_file_lock(dir.path()).expect("first lock must succeed");
1041
1042        let second = std::fs::OpenOptions::new()
1043            .create(true)
1044            .truncate(false)
1045            .write(true)
1046            .open(dir.path().join(".knowledge.lock"))
1047            .unwrap();
1048        assert!(
1049            second.try_lock_exclusive().is_err(),
1050            "a second handle must not acquire the lock while it is held"
1051        );
1052
1053        drop(held);
1054        // `close()` releases the flock synchronously, so the lock IS free here.
1055        // Under heavy parallel test load, however, a single non-blocking
1056        // `try_lock_exclusive()` can momentarily observe `EWOULDBLOCK` from
1057        // scheduling jitter. A short bounded retry removes that flake without
1058        // weakening the guarantee: the lock must become acquirable again.
1059        let mut reacquired = false;
1060        for _ in 0..50 {
1061            if second.try_lock_exclusive().is_ok() {
1062                reacquired = true;
1063                break;
1064            }
1065            std::thread::sleep(std::time::Duration::from_millis(10));
1066        }
1067        assert!(
1068            reacquired,
1069            "lock must be acquirable within 500ms of release"
1070        );
1071    }
1072
1073    #[test]
1074    fn write_json_atomic_leaves_valid_file_and_no_temp() {
1075        let dir = tempfile::tempdir().unwrap();
1076        let path = dir.path().join("knowledge.json");
1077        write_json_atomic(&path, "{\"ok\":true}").unwrap();
1078        assert_eq!(std::fs::read_to_string(&path).unwrap(), "{\"ok\":true}");
1079        let leftover = std::fs::read_dir(dir.path())
1080            .unwrap()
1081            .filter_map(Result::ok)
1082            .any(|e| e.file_name().to_string_lossy().contains(".tmp."));
1083        assert!(!leftover, "no temp file should remain");
1084    }
1085
1086    #[test]
1087    fn load_rebuilds_ephemeral_index_without_changing_json() {
1088        let _isolated = crate::core::data_dir::isolated_data_dir();
1089        let project = tempfile::tempdir().unwrap();
1090        let root = project.path().to_str().unwrap();
1091        let policy = MemoryPolicy::default();
1092        let mut knowledge = ProjectKnowledge::new(root);
1093        knowledge.remember(
1094            "architecture",
1095            "database",
1096            "PostgreSQL",
1097            "test",
1098            0.9,
1099            &policy,
1100        );
1101        knowledge.save().unwrap();
1102
1103        let loaded = ProjectKnowledge::load(root).expect("saved knowledge should load");
1104        assert!(loaded.index.token_positions.contains_key("postgresql"));
1105        assert_eq!(loaded.recall("postgresql").len(), 1);
1106
1107        let json = serde_json::to_string(&loaded).unwrap();
1108        assert!(!json.contains("\"index\""));
1109    }
1110}