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