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        Self::with_store_lock_checked(&hash_project_root(project_root), f)
521    }
522
523    /// [`with_project_lock_checked`](Self::with_project_lock_checked) for
524    /// the store under `hash`.
525    fn with_store_lock_checked<T>(hash: &str, f: impl FnOnce() -> T) -> Result<T, String> {
526        use fs2::FileExt;
527        let dir = knowledge_dir(hash)?;
528        // Parallel writers of this process queue in arrival order and wait
529        // only while the queue stands still; the polled locks below then
530        // bound just the embedding path and other processes. Polled alone,
531        // every writer ahead counted against a waiter's deadline (#2214).
532        let _turn =
533            crate::core::file_lock::take_turn(&dir.join(".knowledge.lock"), KNOWLEDGE_LOCK_WAIT)
534                .ok_or("knowledge lock unavailable")?;
535        let lock = knowledge_lock(hash);
536        let deadline = std::time::Instant::now() + KNOWLEDGE_LOCK_WAIT;
537        let _guard = loop {
538            match lock.try_lock() {
539                Ok(guard) => break guard,
540                Err(std::sync::TryLockError::WouldBlock)
541                    if std::time::Instant::now() < deadline =>
542                {
543                    std::thread::sleep(std::time::Duration::from_millis(5));
544                }
545                Err(_) => return Err("knowledge lock unavailable".into()),
546            }
547        };
548        std::fs::create_dir_all(&dir).map_err(|_| "knowledge directory unavailable")?;
549        let file = crate::core::policy::diagnostics::open_append(&dir.join(".knowledge.lock"))
550            .map_err(|_| "knowledge file lock unavailable")?;
551        loop {
552            match file.try_lock_exclusive() {
553                Ok(()) => break,
554                Err(e)
555                    if crate::core::file_lock::is_contended(&e)
556                        && std::time::Instant::now() < deadline =>
557                {
558                    std::thread::sleep(std::time::Duration::from_millis(5));
559                }
560                Err(_) => return Err("knowledge file lock unavailable".into()),
561            }
562        }
563        let output = f();
564        let _ = FileExt::unlock(&file);
565        Ok(output)
566    }
567
568    pub fn mutate_locked<T>(
569        project_root: &str,
570        f: impl FnOnce(&mut Self) -> T,
571    ) -> Result<(Self, T), String> {
572        let admission = super::protection::KnowledgeAdmission::capture(project_root)?;
573        Self::mutate_locked_with_admission(project_root, &admission, f)
574    }
575
576    pub fn mutate_locked_with_admission<T>(
577        project_root: &str,
578        admission: &super::protection::KnowledgeAdmission,
579        f: impl FnOnce(&mut Self) -> T,
580    ) -> Result<(Self, T), String> {
581        crate::core::providers::provenance::with_reuse_deadline(|| {
582            Self::mutate_locked_in_scope(project_root, admission, f)
583        })
584    }
585
586    fn mutate_locked_in_scope<T>(
587        project_root: &str,
588        admission: &super::protection::KnowledgeAdmission,
589        f: impl FnOnce(&mut Self) -> T,
590    ) -> Result<(Self, T), String> {
591        if Path::new(project_root).is_dir() {
592            crate::core::policy::runtime::with_explicit_project_source_view(
593                Path::new(project_root),
594                |authority| Self::mutate_locked_scoped(project_root, admission, Some(authority), f),
595            )?
596        } else {
597            if crate::core::policy::runtime::inherited_source_view().is_some() {
598                return Err("knowledge project root unavailable".into());
599            }
600            if let Some(request) = crate::core::policy::diagnostics::request_project()
601                && crate::core::pathutil::safe_canonicalize_bounded(&request, 2000)
602                    != crate::core::pathutil::safe_canonicalize_bounded(
603                        Path::new(project_root),
604                        2000,
605                    )
606            {
607                return Err("knowledge project does not match protected request".into());
608            }
609            Self::mutate_locked_scoped(project_root, admission, None, f)
610        }
611    }
612
613    fn mutate_locked_scoped<T>(
614        project_root: &str,
615        admission: &super::protection::KnowledgeAdmission,
616        authority: Option<&crate::core::policy::runtime::PublicationAuthority>,
617        f: impl FnOnce(&mut Self) -> T,
618    ) -> Result<(Self, T), String> {
619        Self::with_project_lock_checked(project_root, || {
620            // An identity change moved this project's hash: its store under
621            // the earlier hash (proven by the recorded root) is copied over
622            // first, so a write never forks the project's knowledge.
623            let current = knowledge_dir(&hash_project_root(project_root))?.join("knowledge.json");
624            if !current.exists()
625                && let Some(old) =
626                    crate::core::legacy_adoption::drifted_knowledge_partition(project_root)
627            {
628                crate::core::legacy_adoption::copy_knowledge_partition(&old, project_root)?;
629            }
630            let raw = Self::load_for_checked_capture(project_root)?;
631            admission.require_safe(&raw)?;
632            let mut knowledge = raw.admit_sources();
633            let out = f(&mut knowledge);
634            admission.require_safe(&knowledge)?;
635            admission.authorize_gateway()?;
636            if let Some(authority) = authority {
637                authority.verify()?;
638            }
639            knowledge.save_with_admission(admission)?;
640            Ok((knowledge.admit_sources(), out))
641        })?
642    }
643
644    /// Removes the facts `remove` selects from `project_root`'s store, under
645    /// the project's locks. Returns how many.
646    ///
647    /// Only a removal: nothing is added or rewritten, so no policy can be
648    /// violated and none is consulted. That keeps it working where an admitted
649    /// write cannot — a checkout deleted since, or a root other than the
650    /// project an MCP request is bound to — so a fail-closed cleanup (e.g.
651    /// Cloud's account scope) does not get stuck on them. A missing store
652    /// removes nothing. Every store is tried: one that cannot be read or
653    /// written (a damaged `knowledge.json`) is named in the error, by its
654    /// file, after the others were cleaned.
655    pub fn remove_facts_locked(
656        project_root: &str,
657        remove: impl Fn(&KnowledgeFact) -> bool,
658    ) -> Result<usize, String> {
659        let mut removed = 0;
660        let mut failed = Vec::new();
661        for hash in Self::stores_of(project_root)? {
662            match Self::remove_from_store(&hash, project_root, &remove) {
663                Ok(n) => removed += n,
664                Err(error) => failed.push(match knowledge_dir(&hash) {
665                    Ok(dir) => format!("{} ({error})", dir.join("knowledge.json").display()),
666                    Err(_) => error,
667                }),
668            }
669        }
670        if failed.is_empty() {
671            Ok(removed)
672        } else {
673            Err(failed.join("; "))
674        }
675    }
676
677    /// The hashes of the stores that hold `project_root`'s knowledge. For an
678    /// existing checkout its own hash. A deleted one no longer hashes to its
679    /// store (the hash folds in the resolved path and the project identity,
680    /// both gone with the folder), so the stores are found by the root they
681    /// record — a clone at the same place later would otherwise get them back.
682    fn stores_of(project_root: &str) -> Result<Vec<String>, String> {
683        let own = hash_project_root(project_root);
684        if Path::new(project_root).is_dir() {
685            return Ok(vec![own]);
686        }
687        let base = crate::core::data_dir::lean_ctx_data_dir()?.join("knowledge");
688        let entries = match std::fs::read_dir(&base) {
689            Ok(entries) => entries,
690            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(vec![]),
691            Err(_) => return Err("knowledge directory unavailable".into()),
692        };
693        let wanted = crate::core::pathutil::normalize_tool_path(project_root);
694        let mut hashes = vec![own];
695        for entry in entries {
696            let entry = entry.map_err(|_| "knowledge directory unavailable")?;
697            let Some(hash) = entry.file_name().to_str().map(str::to_owned) else {
698                continue;
699            };
700            let Ok(store) = parse_store_cached(&entry.path().join("knowledge.json")) else {
701                continue;
702            };
703            if crate::core::pathutil::normalize_tool_path(&store.project_root) == wanted {
704                hashes.push(hash);
705            }
706        }
707        hashes.sort();
708        hashes.dedup();
709        Ok(hashes)
710    }
711
712    fn remove_from_store(
713        hash: &str,
714        project_root: &str,
715        remove: &impl Fn(&KnowledgeFact) -> bool,
716    ) -> Result<usize, String> {
717        let dir = knowledge_dir(hash)?;
718        let path = dir.join("knowledge.json");
719        match std::fs::symlink_metadata(&path) {
720            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0),
721            Err(_) => return Err("knowledge input metadata unavailable".into()),
722            Ok(_) => {}
723        }
724        Self::with_store_lock_checked(hash, || {
725            let mut knowledge = parse_store_cached(&path)?;
726            let canonical = |root: &str| {
727                crate::core::pathutil::safe_canonicalize_bounded(Path::new(root), 2000)
728            };
729            if canonical(&knowledge.project_root) != canonical(project_root) {
730                return Err("knowledge input belongs to a different project".into());
731            }
732            let before = knowledge.facts.clone();
733            knowledge.facts.retain(|f| !remove(f));
734            let removed = before.len() - knowledge.facts.len();
735            if removed == 0 {
736                return Ok(0);
737            }
738            hash.clone_into(&mut knowledge.project_hash);
739            knowledge.rebuild_index();
740            let json = serde_json::to_string_pretty(&knowledge).map_err(|e| e.to_string())?;
741            write_json_atomic(&path, &json)?;
742            super::journal::append(
743                &dir,
744                &super::journal::diff(&before, &knowledge.facts),
745                &UtcDateTime::now().to_rfc3339(),
746            );
747            Ok(removed)
748        })?
749    }
750
751    pub fn load(project_root: &str) -> Option<Self> {
752        let admission = super::protection::KnowledgeAdmission::capture(project_root).ok()?;
753        let legacy_source_safe = |legacy_hash: &str| {
754            let Ok(path) = knowledge_dir(legacy_hash) else {
755                return false;
756            };
757            let path = path.join("knowledge.json");
758            match std::fs::symlink_metadata(&path) {
759                Err(error) if error.kind() == std::io::ErrorKind::NotFound => true,
760                Err(_) => false,
761                Ok(_) => {
762                    let Some(content) =
763                        crate::core::policy::diagnostics::Target::read_store_file(&path)
764                    else {
765                        return false;
766                    };
767                    let Ok(legacy) = serde_json::from_str::<Self>(&content) else {
768                        return false;
769                    };
770                    crate::core::pathutil::safe_canonicalize_bounded(
771                        Path::new(&legacy.project_root),
772                        2000,
773                    ) == crate::core::pathutil::safe_canonicalize_bounded(
774                        Path::new(project_root),
775                        2000,
776                    ) && admission.require_safe(&legacy).is_ok()
777                }
778            }
779        };
780        match super::protection::current(project_root) {
781            Ok(Some(_)) => {
782                let path = knowledge_dir(&hash_project_root(project_root))
783                    .ok()?
784                    .join("knowledge.json");
785                std::fs::symlink_metadata(path).ok()?;
786                let raw = Self::load_for_checked_capture(project_root).ok()?;
787                return admission.view(&raw).ok().map(Self::admit_sources);
788            }
789            Err(_) => return None,
790            Ok(None) => {}
791        }
792        let hash = hash_project_root(project_root);
793        let dir = knowledge_dir(&hash).ok()?;
794        let path = dir.join("knowledge.json");
795
796        if let Ok(mut k) = parse_store_cached(&path) {
797            // The recorded root is the authority; the hash is derived
798            // and is re-keyed for a store copied from an earlier hash.
799            if crate::core::pathutil::safe_canonicalize_bounded(Path::new(&k.project_root), 2000)
800                != crate::core::pathutil::safe_canonicalize_bounded(Path::new(project_root), 2000)
801            {
802                return None;
803            }
804            k.project_hash = hash;
805            k.rebuild_index();
806            return admission.view(&k).ok().map(Self::admit_sources);
807        }
808
809        let old_hash = crate::core::project_hash::hash_path_only(project_root);
810        if old_hash != hash {
811            if !legacy_source_safe(&old_hash) || admission.authorize_gateway().is_err() {
812                return None;
813            }
814            crate::core::project_hash::migrate_if_needed(&old_hash, &hash, project_root);
815            if let Ok(content) = std::fs::read_to_string(&path)
816                && let Ok(mut k) = serde_json::from_str::<Self>(&content)
817            {
818                k.project_hash = hash;
819                k.rebuild_index();
820                if admission.require_safe(&k).is_err()
821                    || admission.authorize_gateway().is_err()
822                    || k.save_with_admission(&admission).is_err()
823                {
824                    return None;
825                }
826                return admission.view(&k).ok().map(Self::admit_sources);
827            }
828        }
829
830        // Migrate stores created before path normalization (issue #325): on
831        // Windows the CLI keyed its store by a backslash path, splitting it from
832        // the forward-slash MCP store. Pull any such legacy store into the
833        // canonical (normalized) location so facts converge.
834        for legacy_hash in crate::core::project_hash::legacy_unnormalized_hashes(project_root) {
835            if legacy_hash == hash {
836                continue;
837            }
838            if !legacy_source_safe(&legacy_hash) || admission.authorize_gateway().is_err() {
839                return None;
840            }
841            crate::core::project_hash::migrate_if_needed(&legacy_hash, &hash, project_root);
842            if let Ok(content) = std::fs::read_to_string(&path)
843                && let Ok(mut k) = serde_json::from_str::<Self>(&content)
844            {
845                k.project_hash = hash;
846                k.rebuild_index();
847                if admission.require_safe(&k).is_err()
848                    || admission.authorize_gateway().is_err()
849                    || k.save_with_admission(&admission).is_err()
850                {
851                    return None;
852                }
853                return admission.view(&k).ok().map(Self::admit_sources);
854            }
855        }
856
857        // The project's identity (git remote, package name, `.lean-ctx-id`)
858        // changed, so its hash moved: a store whose recorded root is this
859        // path is the project's own. Its files are copied (never moved) into
860        // the current partition and pass the same guards as above.
861        if let Some(old_hash) =
862            crate::core::legacy_adoption::drifted_knowledge_partition(project_root)
863        {
864            if !legacy_source_safe(&old_hash) || admission.authorize_gateway().is_err() {
865                return None;
866            }
867            crate::core::legacy_adoption::copy_knowledge_partition(&old_hash, project_root).ok()?;
868            if let Ok(content) = std::fs::read_to_string(&path)
869                && let Ok(mut k) = serde_json::from_str::<Self>(&content)
870                && crate::core::pathutil::safe_canonicalize_bounded(
871                    Path::new(&k.project_root),
872                    2000,
873                ) == crate::core::pathutil::safe_canonicalize_bounded(
874                    Path::new(project_root),
875                    2000,
876                )
877            {
878                k.project_hash = hash;
879                k.rebuild_index();
880                if admission.require_safe(&k).is_err()
881                    || admission.authorize_gateway().is_err()
882                    || k.save_with_admission(&admission).is_err()
883                {
884                    return None;
885                }
886                return admission.view(&k).ok().map(Self::admit_sources);
887            }
888        }
889
890        None
891    }
892
893    pub fn load_or_create(project_root: &str) -> Self {
894        Self::load(project_root).unwrap_or_else(|| Self::new(project_root))
895    }
896
897    /// Migrates legacy knowledge that was accidentally stored under an empty project_root ("")
898    /// into the given `target_root`. Keeps a timestamped backup of the legacy file.
899    pub fn migrate_legacy_empty_root(
900        target_root: &str,
901        policy: &MemoryPolicy,
902    ) -> Result<bool, String> {
903        if target_root.trim().is_empty() {
904            return Ok(false);
905        }
906
907        if super::protection::current(target_root)?.is_some() {
908            return Err("unscoped legacy knowledge requires explicit protected migration".into());
909        }
910        // This explicit compatibility migration may read the old empty-root
911        // store, but general load/save must never treat an empty root as authority.
912        let mut legacy_store = None;
913        for hash in [
914            hash_project_root(""),
915            crate::core::project_hash::hash_path_only(""),
916        ] {
917            let path = knowledge_dir(&hash)?.join("knowledge.json");
918            match std::fs::symlink_metadata(&path) {
919                Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
920                Err(_) => return Err("legacy knowledge input unavailable".into()),
921                Ok(_) => {}
922            }
923            let text = crate::core::policy::diagnostics::Target::read_store_file(&path)
924                .ok_or("legacy knowledge input is uninspectable")?;
925            let legacy: Self =
926                serde_json::from_str(&text).map_err(|_| "invalid legacy knowledge")?;
927            legacy_store = Some((legacy, path));
928            break;
929        }
930        let Some((legacy, legacy_path)) = legacy_store else {
931            return Ok(false);
932        };
933
934        if !legacy.project_root.trim().is_empty() {
935            return Ok(false);
936        }
937        if legacy.facts.is_empty() && legacy.patterns.is_empty() && legacy.history.is_empty() {
938            return Ok(false);
939        }
940
941        Self::with_project_lock_checked(target_root, || {
942            if super::protection::current(target_root)?.is_some() {
943                return Err("legacy migration withheld by changed project policy".into());
944            }
945            let mut target = Self::load_or_create(target_root);
946
947            fn fact_key(f: &KnowledgeFact) -> String {
948                format!(
949                    "{}|{}|{}|{}|{}",
950                    f.category, f.key, f.value, f.source_session, f.created_at
951                )
952            }
953            fn pattern_key(p: &ProjectPattern) -> String {
954                format!(
955                    "{}|{}|{}|{}",
956                    p.pattern_type, p.description, p.source_session, p.created_at
957                )
958            }
959            fn history_key(h: &ConsolidatedInsight) -> String {
960                format!(
961                    "{}|{}|{}",
962                    h.summary,
963                    h.from_sessions.join(","),
964                    h.timestamp
965                )
966            }
967
968            let mut seen_facts: std::collections::HashSet<String> =
969                target.facts.iter().map(fact_key).collect();
970            for f in legacy.facts {
971                if seen_facts.insert(fact_key(&f)) {
972                    target.facts.push(f);
973                }
974            }
975
976            let mut seen_patterns: std::collections::HashSet<String> =
977                target.patterns.iter().map(pattern_key).collect();
978            for p in legacy.patterns {
979                if seen_patterns.insert(pattern_key(&p)) {
980                    target.patterns.push(p);
981                }
982            }
983
984            let mut seen_history: std::collections::HashSet<String> =
985                target.history.iter().map(history_key).collect();
986            for h in legacy.history {
987                if seen_history.insert(history_key(&h)) {
988                    target.history.push(h);
989                }
990            }
991
992            target.facts.sort_by(|a, b| {
993                b.created_at
994                    .cmp(&a.created_at)
995                    .then_with(|| b.confidence.total_cmp(&a.confidence))
996            });
997            target
998                .patterns
999                .sort_by_key(|x| std::cmp::Reverse(x.created_at));
1000            if target.patterns.len() > policy.knowledge.max_patterns {
1001                target.patterns.truncate(policy.knowledge.max_patterns);
1002            }
1003            target
1004                .history
1005                .sort_by_key(|x| std::cmp::Reverse(x.timestamp));
1006            if target.history.len() > policy.knowledge.max_history {
1007                target.history.truncate(policy.knowledge.max_history);
1008            }
1009
1010            target.updated_at = UtcDateTime::now();
1011            if super::protection::current(target_root)?.is_some() {
1012                return Err("legacy migration withheld by changed project policy".into());
1013            }
1014            target.save_unlocked()?;
1015
1016            let legacy_dir = legacy_path.parent().ok_or("legacy directory unavailable")?;
1017            if legacy_path.exists() {
1018                let ts = UtcDateTime::now().format("%Y%m%d-%H%M%S");
1019                let backup = legacy_dir.join(format!("knowledge.legacy-empty-root.{ts}.json"));
1020                std::fs::hard_link(&legacy_path, &backup)
1021                    .map_err(|_| "legacy backup could not be preserved")?;
1022                std::fs::remove_file(&legacy_path)
1023                    .map_err(|_| "legacy backup retained but source cleanup failed")?;
1024            }
1025
1026            Ok(true)
1027        })?
1028    }
1029}
1030
1031#[cfg(test)]
1032mod tests {
1033    use super::*;
1034    #[cfg(feature = "embeddings")]
1035    use fs2::FileExt;
1036
1037    // --- #1802: `auto_capture = false` must hold at the store, not the callers ---
1038
1039    fn machine_fact(category: &str, key: &str) -> KnowledgeFact {
1040        let now = lean_ctx_time::UtcDateTime::now();
1041        KnowledgeFact {
1042            anchors: Vec::new(),
1043            review: None,
1044            capture: Default::default(),
1045            origin: crate::core::knowledge::FactOrigin::Local,
1046            category: category.to_string(),
1047            key: key.to_string(),
1048            value: "Finding: run-guards.ts: Read run-guards.ts (92L)".to_string(),
1049            source_session: "session-1".to_string(),
1050            confidence: 0.8,
1051            created_at: now,
1052            last_confirmed: now,
1053            retrieval_count: 0,
1054            last_retrieved: None,
1055            valid_from: None,
1056            valid_until: None,
1057            supersedes: None,
1058            confirmation_count: 1,
1059            feedback_up: 0,
1060            feedback_down: 0,
1061            last_feedback: None,
1062            privacy: Default::default(),
1063            sensitivity: Default::default(),
1064            imported_from: None,
1065            archetype: Default::default(),
1066            fidelity: None,
1067            revision_count: 0,
1068            status: None,
1069            validity: None,
1070        }
1071    }
1072
1073    #[test]
1074    fn machine_derived_is_recognised_in_either_ingestion_shape() {
1075        // `extract_session_facts` marks the category; `auto_capture` marks the
1076        // key. Both producers must be recognisable by one predicate.
1077        assert!(is_machine_derived("auto:blocker", "run-guards.ts"));
1078        assert!(is_machine_derived("blocker", "auto:config.rs"));
1079        assert!(!is_machine_derived("konventionen", "naming"));
1080        assert!(!is_machine_derived("ops", "deploy"));
1081    }
1082
1083    #[test]
1084    fn a_curated_fact_is_never_affected_by_the_gate() {
1085        // The key disables *automatic* capture. A fact a person wrote must be
1086        // storable whatever the flag says, or the feature would be a footgun.
1087        // Isolated: the store boundary reads the data dir and the active
1088        // policy, which concurrent tests change.
1089        let _data = crate::core::data_dir::isolated_data_dir();
1090        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
1091        let knowledge_root = tempfile::tempdir().unwrap();
1092        let mut knowledge = ProjectKnowledge::new(knowledge_root.path().to_str().unwrap());
1093        assert!(
1094            knowledge.add_fact(machine_fact("konventionen", "naming")),
1095            "curated facts must always be accepted"
1096        );
1097    }
1098
1099    #[test]
1100    fn disabled_capture_blocks_every_machine_derived_shape() {
1101        // The regression: a single MCP call re-materialised deleted `auto:*`
1102        // facts because only one of two producers consulted the flag. Asserting
1103        // at the store covers both, and any producer added later.
1104        let _env = crate::core::data_dir::test_env_lock();
1105        crate::test_env::set_var("LEAN_CTX_AUTO_CAPTURE", "0");
1106
1107        let knowledge_root = tempfile::tempdir().unwrap();
1108
1109        let mut knowledge = ProjectKnowledge::new(knowledge_root.path().to_str().unwrap());
1110        let category_marked = knowledge.add_fact(machine_fact("auto:blocker", "run-guards.ts"));
1111        let key_marked = knowledge.add_fact(machine_fact("blocker", "auto:config.rs"));
1112
1113        crate::test_env::remove_var("LEAN_CTX_AUTO_CAPTURE");
1114
1115        assert!(!category_marked, "auto:* category must be refused");
1116        assert!(!key_marked, "auto:* key must be refused");
1117        assert!(
1118            knowledge.facts.is_empty(),
1119            "nothing machine-derived may reach the durable store"
1120        );
1121    }
1122
1123    #[test]
1124    fn enabled_capture_still_stores_machine_derived_facts() {
1125        let _env = crate::core::data_dir::test_env_lock();
1126        crate::test_env::set_var("LEAN_CTX_AUTO_CAPTURE", "1");
1127
1128        let knowledge_root = tempfile::tempdir().unwrap();
1129
1130        let mut knowledge = ProjectKnowledge::new(knowledge_root.path().to_str().unwrap());
1131        let stored = knowledge.add_fact(machine_fact("auto:blocker", "run-guards.ts"));
1132
1133        crate::test_env::remove_var("LEAN_CTX_AUTO_CAPTURE");
1134
1135        assert!(stored, "the default behaviour must be unchanged");
1136    }
1137
1138    #[test]
1139    fn disabled_capture_does_not_refresh_existing_machine_facts() {
1140        // Facts from an earlier enabled run stay on disk — the fix stops new
1141        // writes, it does not delete history. But a disabled run must not keep
1142        // touching them either, or they would look perpetually fresh to the
1143        // lifecycle and never age out.
1144        let _env = crate::core::data_dir::test_env_lock();
1145        crate::test_env::set_var("LEAN_CTX_AUTO_CAPTURE", "1");
1146        let knowledge_root = tempfile::tempdir().unwrap();
1147        let mut knowledge = ProjectKnowledge::new(knowledge_root.path().to_str().unwrap());
1148        knowledge.add_fact(machine_fact("auto:blocker", "run-guards.ts"));
1149        let confirmed_while_enabled = knowledge.facts[0].last_confirmed;
1150
1151        crate::test_env::set_var("LEAN_CTX_AUTO_CAPTURE", "0");
1152        let refreshed = knowledge.add_fact(machine_fact("auto:blocker", "run-guards.ts"));
1153        crate::test_env::remove_var("LEAN_CTX_AUTO_CAPTURE");
1154
1155        assert!(!refreshed);
1156        assert_eq!(knowledge.facts.len(), 1);
1157        assert_eq!(
1158            knowledge.facts[0].last_confirmed, confirmed_while_enabled,
1159            "a refused write must not refresh the existing fact"
1160        );
1161    }
1162
1163    #[cfg(feature = "embeddings")]
1164    #[test]
1165    fn file_lock_is_exclusive_across_handles() {
1166        // flock-style locks are tied to the open file description, so two
1167        // independent `open()`s in the same process behave like two separate
1168        // processes: while the first holds the exclusive lock, the second must
1169        // fail to acquire it. This validates the cross-process guarantee that
1170        // protects parallel CLI writes (issue #326).
1171        let dir = tempfile::tempdir().unwrap();
1172        let held = acquire_file_lock(dir.path()).expect("first lock must succeed");
1173
1174        let second = std::fs::OpenOptions::new()
1175            .create(true)
1176            .truncate(false)
1177            .write(true)
1178            .open(dir.path().join(".knowledge.lock"))
1179            .unwrap();
1180        assert!(
1181            second.try_lock_exclusive().is_err(),
1182            "a second handle must not acquire the lock while it is held"
1183        );
1184
1185        drop(held);
1186        // `close()` releases the flock synchronously, so the lock IS free here.
1187        // Under heavy parallel test load, however, a single non-blocking
1188        // `try_lock_exclusive()` can momentarily observe `EWOULDBLOCK` from
1189        // scheduling jitter. A short bounded retry removes that flake without
1190        // weakening the guarantee: the lock must become acquirable again.
1191        let mut reacquired = false;
1192        for _ in 0..50 {
1193            if second.try_lock_exclusive().is_ok() {
1194                reacquired = true;
1195                break;
1196            }
1197            std::thread::sleep(std::time::Duration::from_millis(10));
1198        }
1199        assert!(
1200            reacquired,
1201            "lock must be acquirable within 500ms of release"
1202        );
1203    }
1204
1205    #[test]
1206    fn write_json_atomic_leaves_valid_file_and_no_temp() {
1207        let dir = tempfile::tempdir().unwrap();
1208        let path = dir.path().join("knowledge.json");
1209        write_json_atomic(&path, "{\"ok\":true}").unwrap();
1210        assert_eq!(std::fs::read_to_string(&path).unwrap(), "{\"ok\":true}");
1211        let leftover = std::fs::read_dir(dir.path())
1212            .unwrap()
1213            .filter_map(Result::ok)
1214            .any(|e| e.file_name().to_string_lossy().contains(".tmp."));
1215        assert!(!leftover, "no temp file should remain");
1216    }
1217
1218    #[test]
1219    fn load_rebuilds_ephemeral_index_without_changing_json() {
1220        let _isolated = crate::core::data_dir::isolated_data_dir();
1221        let project = tempfile::tempdir().unwrap();
1222        let root = project.path().to_str().unwrap();
1223        let policy = MemoryPolicy::default();
1224        let mut knowledge = ProjectKnowledge::new(root);
1225        knowledge.remember(
1226            "architecture",
1227            "database",
1228            "PostgreSQL",
1229            "test",
1230            0.9,
1231            &policy,
1232        );
1233        knowledge.save().unwrap();
1234
1235        let loaded = ProjectKnowledge::load(root).expect("saved knowledge should load");
1236        assert!(loaded.index.token_positions.contains_key("postgresql"));
1237        assert_eq!(loaded.recall("postgresql").len(), 1);
1238
1239        let json = serde_json::to_string(&loaded).unwrap();
1240        assert!(!json.contains("\"index\""));
1241    }
1242}