Skip to main content

lean_ctx/core/knowledge/
persist.rs

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