Skip to main content

lean_ctx/core/
shared_context.rs

1//! Durable facts agents share through `ctx_memory`, partitioned by project.
2//!
3//! Each project has its own `shared_context/<project hash>.jsonl` in the
4//! LeanCTX data directory, and every entry records the project it was stored
5//! for; that stored root, not the file name, decides whether an entry is
6//! served. Releases before 3.11.5 kept one installation-wide
7//! `~/.local/share/lean-ctx/shared_context.jsonl` without a project. Those
8//! entries carry no provable scope: the file is left in place, unread, and is
9//! never served to any project.
10
11use std::collections::{BTreeMap, HashSet};
12use std::fs;
13use std::io::{BufRead, BufReader};
14use std::path::{Path, PathBuf};
15use std::time::{SystemTime, UNIX_EPOCH};
16
17use serde::{Deserialize, Serialize};
18
19/// A fact shared between independent agent sessions.
20#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
21pub struct SharedContextEntry {
22    pub id: String,
23    pub content: String,
24    pub agent: String,
25    pub timestamp: u64,
26    pub category: String,
27    /// Confidence assigned to this fact, from 0.0 (untrusted) to 1.0 (certain).
28    #[serde(default = "default_confidence")]
29    pub confidence: f32,
30    pub access_count: u32,
31    pub last_accessed: u64,
32    /// Unix timestamp when an outcome last confirmed this fact.
33    #[serde(default)]
34    pub last_verified: Option<u64>,
35    /// Number of successful verification events recorded for this fact.
36    #[serde(default)]
37    pub verification_count: u32,
38    /// Exponential-moving-average correlation between this fact and successful outcomes.
39    #[serde(default)]
40    pub outcome_correlation: f32,
41    /// Optional per-fact verification window before the fact becomes stale.
42    #[serde(default)]
43    pub stale_after_days: Option<u16>,
44    /// Agent or user that first added this fact.
45    #[serde(default)]
46    pub created_by: String,
47    /// Hash of the fact that supersedes this one.
48    #[serde(default)]
49    pub superseded_by: Option<String>,
50    /// The project this fact was stored for; the only authority for serving it.
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub project_root: Option<String>,
53}
54
55/// Backward-compatible name for an entry in shared fact memory.
56pub type FactEntry = SharedContextEntry;
57
58/// Summary of the contents of a [`SharedContext`] store.
59#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
60pub struct SharedContextStats {
61    pub total_entries: usize,
62    pub unique_agents: usize,
63    pub categories: BTreeMap<String, usize>,
64    pub total_accesses: u64,
65}
66
67/// Quality and contributor summary across shared-memory sessions.
68#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
69pub struct MemoryStats {
70    pub total_facts: usize,
71    pub verified_pct: f32,
72    pub avg_confidence: f32,
73    /// Contributors ordered by descending fact count, then contributor name.
74    pub top_contributors: Vec<(String, usize)>,
75}
76
77/// Durable cross-agent memory backed by an appendable JSONL file.
78#[derive(Debug, Clone)]
79pub struct SharedContext {
80    path: PathBuf,
81    /// Set for a project partition: only entries stored for this root load.
82    project_root: Option<String>,
83}
84
85impl SharedContext {
86    /// An unpartitioned store at `path` (tests and explicit tooling).
87    pub fn new(path: PathBuf) -> Self {
88        Self {
89            path,
90            project_root: None,
91        }
92    }
93
94    /// The installation-wide store of releases before 3.11.5. Served to no
95    /// project; read for the explicit `lean-ctx migrate legacy-context`
96    /// adoption only.
97    pub fn legacy() -> Option<Self> {
98        // Those releases wrote under `dirs::home_dir()`. Tests redirect the
99        // home through `HOME`, which `dirs` ignores on Windows (known folder):
100        // without this they would share the runner's real profile.
101        #[cfg(not(test))]
102        let home = dirs::home_dir();
103        #[cfg(test)]
104        let home = crate::core::home::resolve_home_dir();
105        home.map(|home| Self::new(home.join(".local/share/lean-ctx/shared_context.jsonl")))
106    }
107
108    /// Facts left in a partition that is no longer the current one of the
109    /// root they recorded: that project's identity (remote, package name)
110    /// changed since. Served to no project until adopted.
111    pub(crate) fn orphaned_entries() -> Vec<(PathBuf, SharedContextEntry)> {
112        let Ok(dir) = crate::core::data_dir::lean_ctx_data_dir().map(|d| d.join("shared_context"))
113        else {
114            return Vec::new();
115        };
116        let Ok(files) = fs::read_dir(&dir) else {
117            return Vec::new();
118        };
119        let mut paths: Vec<PathBuf> = files
120            .flatten()
121            .map(|file| file.path())
122            .filter(|path| path.extension().is_some_and(|ext| ext == "jsonl"))
123            .collect();
124        paths.sort();
125        let mut orphaned = Vec::new();
126        for path in paths {
127            let stem = path
128                .file_stem()
129                .map(|stem| stem.to_string_lossy().into_owned())
130                .unwrap_or_default();
131            for entry in Self::new(path.clone()).load().unwrap_or_default() {
132                if entry
133                    .project_root
134                    .as_deref()
135                    .is_some_and(|root| crate::core::project_hash::hash_project_root(root) != stem)
136                {
137                    orphaned.push((path.clone(), entry));
138                }
139            }
140        }
141        orphaned
142    }
143
144    /// The orphaned facts that recorded `project_root` (canonically).
145    pub(crate) fn drifted_entries(project_root: &str) -> Vec<(PathBuf, SharedContextEntry)> {
146        let canonical =
147            |root: &str| crate::core::pathutil::safe_canonicalize_bounded(Path::new(root), 2000);
148        let wanted = canonical(project_root);
149        Self::orphaned_entries()
150            .into_iter()
151            .filter(|(_, entry)| {
152                entry
153                    .project_root
154                    .as_deref()
155                    .is_some_and(|root| canonical(root) == wanted)
156            })
157            .collect()
158    }
159
160    /// The shared facts of `project_root`, in its own partition of the data
161    /// directory.
162    pub fn for_project(project_root: &str) -> Result<Self, String> {
163        if project_root.trim().is_empty() {
164            return Err("shared memory needs a project".into());
165        }
166        let path = crate::core::data_dir::lean_ctx_data_dir()?
167            .join("shared_context")
168            .join(format!(
169                "{}.jsonl",
170                crate::core::project_hash::hash_project_root(project_root)
171            ));
172        Ok(Self {
173            path,
174            project_root: Some(project_root.to_string()),
175        })
176    }
177
178    pub fn path(&self) -> &Path {
179        &self.path
180    }
181
182    pub fn put(
183        &self,
184        content: impl Into<String>,
185        agent: impl Into<String>,
186        category: impl Into<String>,
187    ) -> Result<String, String> {
188        let content = content.into();
189        let agent = agent.into();
190        let category = normalize_category(&category.into())?;
191        let id = blake3::hash(content.as_bytes()).to_hex().to_string();
192        let now = unix_timestamp();
193        let _writer = self.write_lock()?;
194        let mut entries = self.load()?;
195
196        if let Some(existing) = entries.iter_mut().find(|entry| entry.id == id) {
197            existing.agent.clone_from(&agent);
198            existing.category.clone_from(&category);
199            existing.timestamp = now;
200            existing.last_accessed = now;
201            self.save(&entries)?;
202            return Ok(id);
203        }
204
205        entries.push(SharedContextEntry {
206            id: id.clone(),
207            content,
208            agent: agent.clone(),
209            timestamp: now,
210            category,
211            confidence: default_confidence(),
212            access_count: 0,
213            last_accessed: now,
214            last_verified: None,
215            verification_count: 0,
216            outcome_correlation: 0.0,
217            stale_after_days: None,
218            created_by: agent,
219            superseded_by: None,
220            project_root: self.project_root.clone(),
221        });
222        self.save(&entries)?;
223        Ok(id)
224    }
225
226    pub fn get_relevant(
227        &self,
228        query: &str,
229        limit: usize,
230    ) -> Result<Vec<SharedContextEntry>, String> {
231        if limit == 0 {
232            return Ok(Vec::new());
233        }
234        let _writer = self.write_lock()?;
235        let mut entries = self.load()?;
236        let query_terms = terms(query);
237        if query_terms.is_empty() {
238            return Ok(Vec::new());
239        }
240        let document_count = entries.len() as f64;
241        let average_length = entries
242            .iter()
243            .map(|entry| terms(&entry.content).len() as f64)
244            .sum::<f64>()
245            / document_count.max(1.0);
246        let document_frequency = query_terms
247            .iter()
248            .map(|term| {
249                (
250                    term,
251                    entries
252                        .iter()
253                        .filter(|entry| terms(&entry.content).contains(term))
254                        .count() as f64,
255                )
256            })
257            .collect::<BTreeMap<_, _>>();
258
259        let mut scored = entries
260            .iter()
261            .enumerate()
262            .filter_map(|(index, entry)| {
263                let entry_terms = terms(&entry.content);
264                let length = entry_terms.len() as f64;
265                let score = query_terms.iter().fold(0.0, |score, term| {
266                    let frequency =
267                        entry_terms.iter().filter(|value| *value == term).count() as f64;
268                    if frequency == 0.0 {
269                        return score;
270                    }
271                    let df = document_frequency.get(term).copied().unwrap_or_default();
272                    let idf = ((document_count - df + 0.5) / (df + 0.5) + 1.0).ln();
273                    let k1 = 1.2;
274                    let b = 0.75;
275                    score
276                        + idf * frequency * (k1 + 1.0)
277                            / (frequency + k1 * (1.0 - b + b * length / average_length.max(1.0)))
278                });
279                (score > 0.0).then_some((index, score))
280            })
281            .collect::<Vec<_>>();
282        scored.sort_by(|left, right| {
283            right
284                .1
285                .total_cmp(&left.1)
286                .then_with(|| left.0.cmp(&right.0))
287        });
288
289        let now = unix_timestamp();
290        let selected = scored
291            .into_iter()
292            .take(limit)
293            .map(|(index, _)| index)
294            .collect::<Vec<_>>();
295        for index in &selected {
296            let entry = &mut entries[*index];
297            entry.access_count = entry.access_count.saturating_add(1);
298            entry.last_accessed = now;
299        }
300        let results = selected
301            .into_iter()
302            .map(|index| entries[index].clone())
303            .collect();
304        self.save(&entries)?;
305        Ok(results)
306    }
307
308    pub fn get_recent(&self, limit: usize) -> Result<Vec<SharedContextEntry>, String> {
309        let mut entries = self.load()?;
310        entries.sort_by(|left, right| {
311            right
312                .timestamp
313                .cmp(&left.timestamp)
314                .then_with(|| right.id.cmp(&left.id))
315        });
316        Ok(entries.into_iter().take(limit).collect())
317    }
318
319    pub fn get_by_category(&self, category: &str) -> Result<Vec<SharedContextEntry>, String> {
320        let category = normalize_category(category)?;
321        let mut entries = self
322            .load()?
323            .into_iter()
324            .filter(|entry| entry.category == category)
325            .collect::<Vec<_>>();
326        entries.sort_by(|left, right| {
327            right
328                .timestamp
329                .cmp(&left.timestamp)
330                .then_with(|| right.id.cmp(&left.id))
331        });
332        Ok(entries)
333    }
334
335    pub fn prune(&self, max_age_seconds: u64, max_entries: usize) -> Result<usize, String> {
336        let now = unix_timestamp();
337        let _writer = self.write_lock()?;
338        let mut entries = self.load()?;
339        let original_len = entries.len();
340        entries.retain(|entry| now.saturating_sub(entry.last_accessed) <= max_age_seconds);
341        entries.sort_by(|left, right| {
342            right
343                .last_accessed
344                .cmp(&left.last_accessed)
345                .then_with(|| right.access_count.cmp(&left.access_count))
346                .then_with(|| right.timestamp.cmp(&left.timestamp))
347        });
348        entries.truncate(max_entries);
349        let removed = original_len.saturating_sub(entries.len());
350        self.save(&entries)?;
351        Ok(removed)
352    }
353
354    /// Record an explicit confirmation of a fact.
355    pub fn verify_fact(&self, hash: &str) -> Result<(), String> {
356        let _writer = self.write_lock()?;
357        let mut entries = self.load()?;
358        let entry = find_fact_mut(&mut entries, hash)?;
359        entry.last_verified = Some(unix_timestamp());
360        entry.verification_count = entry.verification_count.saturating_add(1);
361        self.save(&entries)
362    }
363
364    /// Lower the confidence of a fact identified as stale without removing it.
365    pub fn mark_stale(&self, hash: &str) -> Result<(), String> {
366        let _writer = self.write_lock()?;
367        let mut entries = self.load()?;
368        find_fact_mut(&mut entries, hash)?.confidence = 0.3;
369        self.save(&entries)
370    }
371
372    /// Mark `old_hash` as replaced by the existing fact identified by `new_fact`.
373    pub fn supersede(&self, old_hash: &str, new_fact: &str) -> Result<(), String> {
374        let _writer = self.write_lock()?;
375        let mut entries = self.load()?;
376        if old_hash == new_fact {
377            return Err("a fact cannot supersede itself".to_string());
378        }
379        if !entries.iter().any(|entry| entry.id == new_fact) {
380            return Err(format!("fact '{new_fact}' does not exist"));
381        }
382        find_fact_mut(&mut entries, old_hash)?.superseded_by = Some(new_fact.to_string());
383        self.save(&entries)
384    }
385
386    /// Remove facts whose latest verification (or creation) predates their expiry window.
387    pub fn prune_stale(&self, max_age_days: u16) -> Result<usize, String> {
388        let now = unix_timestamp();
389        let _writer = self.write_lock()?;
390        let mut entries = self.load()?;
391        let original_len = entries.len();
392        entries.retain(|entry| {
393            let age_days = entry.stale_after_days.unwrap_or(max_age_days);
394            let reference_time = entry.last_verified.unwrap_or(entry.timestamp);
395            now.saturating_sub(reference_time) <= u64::from(age_days) * SECONDS_PER_DAY
396        });
397        let removed = original_len.saturating_sub(entries.len());
398        self.save(&entries)?;
399        Ok(removed)
400    }
401
402    /// Remove facts consistently associated with unsuccessful outcomes.
403    pub fn prune_negative(&self) -> Result<usize, String> {
404        let _writer = self.write_lock()?;
405        let mut entries = self.load()?;
406        let original_len = entries.len();
407        entries.retain(|entry| entry.outcome_correlation >= NEGATIVE_CORRELATION_THRESHOLD);
408        let removed = original_len.saturating_sub(entries.len());
409        self.save(&entries)?;
410        Ok(removed)
411    }
412
413    /// Return query-matching facts ordered by their provenance quality score.
414    pub fn get_best(&self, query: &str, limit: usize) -> Result<Vec<SharedContextEntry>, String> {
415        if limit == 0 {
416            return Ok(Vec::new());
417        }
418        let _writer = self.write_lock()?;
419        let mut entries = self.load()?;
420        let query_terms = terms(query);
421        if query_terms.is_empty() {
422            return Ok(Vec::new());
423        }
424
425        let mut matches = entries
426            .iter()
427            .enumerate()
428            .filter_map(|(index, entry)| {
429                let entry_terms = terms(&entry.content);
430                let relevance = query_terms
431                    .iter()
432                    .filter(|term| entry_terms.contains(term))
433                    .count();
434                (relevance > 0).then_some((index, relevance))
435            })
436            .collect::<Vec<_>>();
437        matches.sort_by(|left, right| {
438            let left_quality = entries[left.0].confidence * entries[left.0].outcome_correlation;
439            let right_quality = entries[right.0].confidence * entries[right.0].outcome_correlation;
440            right_quality
441                .total_cmp(&left_quality)
442                .then_with(|| right.1.cmp(&left.1))
443                .then_with(|| entries[left.0].id.cmp(&entries[right.0].id))
444        });
445
446        let now = unix_timestamp();
447        let selected = matches
448            .into_iter()
449            .take(limit)
450            .map(|(index, _)| index)
451            .collect::<Vec<_>>();
452        for index in &selected {
453            let entry = &mut entries[*index];
454            entry.access_count = entry.access_count.saturating_add(1);
455            entry.last_accessed = now;
456        }
457        let results = selected
458            .into_iter()
459            .map(|index| entries[index].clone())
460            .collect();
461        self.save(&entries)?;
462        Ok(results)
463    }
464
465    /// Fold an outcome into a fact's correlation score with an exponential moving average.
466    pub fn record_fact_outcome(&self, hash: &str, success: bool) -> Result<(), String> {
467        let _writer = self.write_lock()?;
468        let mut entries = self.load()?;
469        let entry = find_fact_mut(&mut entries, hash)?;
470        let outcome = if success { 1.0 } else { -1.0 };
471        entry.outcome_correlation = (entry.outcome_correlation * (1.0 - OUTCOME_EMA_ALPHA)
472            + outcome * OUTCOME_EMA_ALPHA)
473            .clamp(-1.0, 1.0);
474        self.save(&entries)
475    }
476
477    /// Summarize provenance quality and the agents or users that contributed facts.
478    pub fn cross_session_stats(&self) -> Result<MemoryStats, String> {
479        let entries = self.load()?;
480        let total_facts = entries.len();
481        let verified = entries
482            .iter()
483            .filter(|entry| entry.verification_count > 0)
484            .count();
485        let avg_confidence = (total_facts > 0).then(|| {
486            entries.iter().map(|entry| entry.confidence).sum::<f32>() / total_facts as f32
487        });
488        let mut contributors = BTreeMap::new();
489        for entry in &entries {
490            let contributor = if entry.created_by.is_empty() {
491                &entry.agent
492            } else {
493                &entry.created_by
494            };
495            *contributors.entry(contributor.clone()).or_insert(0) += 1;
496        }
497        let mut top_contributors = contributors.into_iter().collect::<Vec<_>>();
498        top_contributors
499            .sort_by(|left, right| right.1.cmp(&left.1).then_with(|| left.0.cmp(&right.0)));
500
501        Ok(MemoryStats {
502            total_facts,
503            verified_pct: percentage(verified, total_facts),
504            avg_confidence: avg_confidence.unwrap_or(0.0),
505            top_contributors,
506        })
507    }
508
509    pub fn stats(&self) -> Result<SharedContextStats, String> {
510        let entries = self.load()?;
511        let unique_agents = entries
512            .iter()
513            .map(|entry| entry.agent.as_str())
514            .collect::<HashSet<_>>()
515            .len();
516        let mut categories = BTreeMap::new();
517        for entry in &entries {
518            *categories.entry(entry.category.clone()).or_insert(0) += 1;
519        }
520        Ok(SharedContextStats {
521            total_entries: entries.len(),
522            unique_agents,
523            categories,
524            total_accesses: entries
525                .iter()
526                .map(|entry| u64::from(entry.access_count))
527                .sum(),
528        })
529    }
530
531    /// Every read-modify-write of this store holds an exclusive lock on a
532    /// sibling `.lock` file from its load to its save, so writers in other
533    /// threads or processes (two agents of one project) cannot replace the
534    /// file with a copy that lacks their entries. Released on drop.
535    fn write_lock(&self) -> Result<fs::File, String> {
536        let lock_path = self.path.with_extension("lock");
537        if let Some(parent) = lock_path.parent() {
538            fs::create_dir_all(parent)
539                .map_err(|error| format!("create {}: {error}", parent.display()))?;
540        }
541        // Windows `LockFileEx` needs a handle with GENERIC_READ or
542        // GENERIC_WRITE; an append-only handle lacks FILE_WRITE_DATA, so every
543        // lock attempt failed with "Access is denied" (os error 5).
544        let file = fs::OpenOptions::new()
545            .create(true)
546            .read(true)
547            .write(true)
548            .truncate(false)
549            .open(&lock_path)
550            .map_err(|error| format!("open {}: {error}", lock_path.display()))?;
551        crate::core::file_lock::acquire_exclusive_timeout(&file, WRITE_LOCK_WAIT)
552            .map_err(|error| format!("shared memory is busy: {error}"))?;
553        Ok(file)
554    }
555
556    fn load(&self) -> Result<Vec<SharedContextEntry>, String> {
557        if !self.path.exists() {
558            return Ok(Vec::new());
559        }
560        let file = fs::File::open(&self.path)
561            .map_err(|error| format!("open {}: {error}", self.path.display()))?;
562        let mut entries = BufReader::new(file)
563            .lines()
564            .filter(|line| line.as_ref().is_ok_and(|value| !value.trim().is_empty()))
565            .map(|line| {
566                let line =
567                    line.map_err(|error| format!("read {}: {error}", self.path.display()))?;
568                serde_json::from_str(&line)
569                    .map_err(|error| format!("parse {}: {error}", self.path.display()))
570            })
571            .collect::<Result<Vec<SharedContextEntry>, String>>()?;
572        for entry in &mut entries {
573            apply_provenance_defaults(entry);
574        }
575        if let Some(root) = &self.project_root {
576            // The file name is a hash; the stored root is the authority.
577            entries.retain(|entry| {
578                entry
579                    .project_root
580                    .as_deref()
581                    .is_some_and(|stored| same_root(stored, root))
582            });
583        }
584        Ok(entries)
585    }
586
587    fn save(&self, entries: &[SharedContextEntry]) -> Result<(), String> {
588        let parent = self
589            .path
590            .parent()
591            .ok_or_else(|| format!("{} has no parent", self.path.display()))?;
592        fs::create_dir_all(parent)
593            .map_err(|error| format!("create {}: {error}", parent.display()))?;
594        let mut content = String::new();
595        for entry in entries {
596            content.push_str(
597                &serde_json::to_string(entry)
598                    .map_err(|error| format!("serialize entry: {error}"))?,
599            );
600            content.push('\n');
601        }
602        crate::config_io::write_atomic(&self.path, &content)
603            .map_err(|error| format!("replace {}: {error}", self.path.display()))
604    }
605}
606
607fn same_root(stored: &str, requested: &str) -> bool {
608    use crate::core::pathutil::normalize_tool_path;
609    normalize_tool_path(stored).trim_end_matches('/')
610        == normalize_tool_path(requested).trim_end_matches('/')
611}
612
613/// How long a writer waits for another writer of the same store.
614const WRITE_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
615const SECONDS_PER_DAY: u64 = 24 * 60 * 60;
616const NEGATIVE_CORRELATION_THRESHOLD: f32 = -0.3;
617const OUTCOME_EMA_ALPHA: f32 = 0.2;
618
619fn default_confidence() -> f32 {
620    0.8
621}
622
623fn find_fact_mut<'a>(
624    entries: &'a mut [SharedContextEntry],
625    hash: &str,
626) -> Result<&'a mut SharedContextEntry, String> {
627    entries
628        .iter_mut()
629        .find(|entry| entry.id == hash)
630        .ok_or_else(|| format!("fact '{hash}' does not exist"))
631}
632
633fn apply_provenance_defaults(entry: &mut SharedContextEntry) {
634    entry.confidence = entry.confidence.clamp(0.0, 1.0);
635    entry.outcome_correlation = entry.outcome_correlation.clamp(-1.0, 1.0);
636    if entry.created_by.is_empty() {
637        entry.created_by.clone_from(&entry.agent);
638    }
639}
640
641fn percentage(numerator: usize, denominator: usize) -> f32 {
642    if denominator == 0 {
643        0.0
644    } else {
645        numerator as f32 / denominator as f32 * 100.0
646    }
647}
648
649fn normalize_category(category: &str) -> Result<String, String> {
650    match category {
651        "fact" | "decision" | "blocker" | "pattern" => Ok(category.to_string()),
652        other => Err(format!(
653            "invalid category '{other}' (expected fact|decision|blocker|pattern)"
654        )),
655    }
656}
657
658fn terms(value: &str) -> Vec<String> {
659    value
660        .split(|character: char| !character.is_alphanumeric())
661        .filter(|term| !term.is_empty())
662        .map(str::to_lowercase)
663        .collect()
664}
665
666/// The newest shared facts of `project_root` as a context hint, re-admitted
667/// under the originless rule; nothing when the project has none or the hint
668/// may not be served now.
669pub fn session_start_hint(project_root: &str) -> Option<String> {
670    crate::core::legacy_adoption::auto_adopt_shared_context(project_root);
671    let entries = SharedContext::for_project(project_root)
672        .ok()?
673        .get_recent(3)
674        .ok()?;
675    if entries.is_empty() {
676        return None;
677    }
678    let facts = entries
679        .iter()
680        .map(|entry| format!("- [{} · {}] {}", entry.category, entry.agent, entry.content))
681        .collect::<Vec<_>>()
682        .join("\n");
683    crate::tools::admitted_sources::serve_originless(
684        &format!("--- SHARED CONTEXT ---\n{facts}"),
685        "shared memory",
686    )
687    .ok()
688}
689
690fn unix_timestamp() -> u64 {
691    SystemTime::now()
692        .duration_since(UNIX_EPOCH)
693        .map_or(0, |duration| duration.as_secs())
694}
695
696#[cfg(test)]
697mod tests {
698    use super::*;
699
700    fn store(name: &str) -> SharedContext {
701        let path = std::env::temp_dir().join(format!(
702            "lean-ctx-shared-context-{name}-{}.jsonl",
703            uuid::Uuid::new_v4()
704        ));
705        SharedContext::new(path)
706    }
707
708    /// AP05-G2: one installation-wide file served every project's facts, and
709    /// the session hint decorated every tool result with them.
710    #[test]
711    fn shared_facts_and_hint_stay_in_their_project() {
712        let _data = crate::core::data_dir::isolated_data_dir();
713        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
714        let a = tempfile::tempdir().unwrap();
715        let b = tempfile::tempdir().unwrap();
716        let (a, b) = (a.path().to_str().unwrap(), b.path().to_str().unwrap());
717        SharedContext::for_project(a)
718            .unwrap()
719            .put("project-a-marker lives in net/retry.rs", "codex", "fact")
720            .unwrap();
721        let foreign = SharedContext::for_project(b).unwrap();
722        assert!(foreign.get_recent(10).unwrap().is_empty());
723        assert!(
724            foreign
725                .get_relevant("project-a-marker", 10)
726                .unwrap()
727                .is_empty()
728        );
729        assert_eq!(session_start_hint(b), None);
730        let own = session_start_hint(a).expect("own project hint");
731        assert!(own.contains("project-a-marker"), "{own}");
732    }
733
734    /// Several projects through several stores at once, in one data
735    /// directory (AP01 §1/§3; ABNAHME I02, C01): a scope that leaks through
736    /// process-wide state (cwd, environment, a "current project" global) or a
737    /// store without a writer lock shows up as a value in the wrong partition
738    /// or as a lost acknowledged write.
739    mod partitions {
740        use std::collections::BTreeSet;
741        use std::path::PathBuf;
742        use std::sync::{Arc, Barrier};
743
744        use crate::core::agents::AgentRegistry;
745        use crate::core::knowledge::ProjectKnowledge;
746        use crate::core::memory_policy::MemoryPolicy;
747        use crate::core::session::{SessionState, TaskInfo};
748        use crate::core::shared_context::SharedContext;
749
750        /// The same fact keys in every project: a partition mix-up overwrites.
751        const KEYS: [&str; 4] = ["db", "queue", "cache", "auth"];
752
753        fn in_project<T>(root: &str, f: impl FnOnce() -> T) -> T {
754            crate::core::policy::runtime::REQUEST_PROJECT
755                .sync_scope(std::cell::RefCell::new(Some(PathBuf::from(root))), f)
756        }
757
758        fn project(dir: &tempfile::TempDir, name: &str) -> String {
759            let root = dir.path().join(name);
760            std::fs::create_dir_all(&root).unwrap();
761            root.canonicalize().unwrap().to_string_lossy().into_owned()
762        }
763
764        /// Every write one writer makes, each acknowledged before the writer ends.
765        fn write_everywhere(root: &str, key: &str, value: &str) {
766            in_project(root, || {
767                let policy = MemoryPolicy::default();
768                let (knowledge, ()) = ProjectKnowledge::mutate_locked(root, |k| {
769                    k.remember("decision", key, value, "partition-test", 0.9, &policy);
770                })
771                .expect("knowledge write acknowledged");
772                let fact = knowledge
773                    .facts
774                    .iter()
775                    .find(|f| f.key == key && f.value == value)
776                    .cloned()
777                    .expect("acknowledged fact is in the returned store");
778                crate::core::memory_lifecycle::archive_facts(&[fact])
779                    .expect("archive acknowledged");
780                SharedContext::for_project(root)
781                    .and_then(|store| store.put(format!("{key} {value}"), key, "decision"))
782                    .expect("shared memory write acknowledged");
783                let mut session = SessionState::new();
784                session.project_root = Some(root.to_owned());
785                session.task = Some(TaskInfo {
786                    description: value.to_owned(),
787                    intent: None,
788                    progress_pct: None,
789                });
790                session.save().expect("session save acknowledged");
791                // The registry lock is a polled try-lock (750 ms, not a fair
792                // queue, GitLab #1295): with every writer released by one
793                // barrier, a write can be refused under load. A refused write
794                // was never acknowledged and is retried; the property under
795                // test is that no acknowledged write is lost.
796                let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
797                loop {
798                    match AgentRegistry::mutate_locked(|registry| {
799                        registry.share_knowledge(
800                            root,
801                            key,
802                            "decision",
803                            &[(key.into(), value.into())],
804                        )
805                    }) {
806                        Ok((_, shared)) => {
807                            shared.expect("shared knowledge acknowledged");
808                            break;
809                        }
810                        Err(error)
811                            if error.contains("timed out")
812                                && std::time::Instant::now() < deadline => {}
813                        Err(error) => panic!("registry lock: {error}"),
814                    }
815                }
816            });
817        }
818
819        /// What each store of `root` holds now, as one set of values per store.
820        fn partition_contents(root: &str) -> Vec<(&'static str, BTreeSet<String>)> {
821            in_project(root, || {
822                let knowledge: BTreeSet<String> = ProjectKnowledge::load(root)
823                    .map(|k| {
824                        k.facts
825                            .iter()
826                            .filter(|f| f.is_current())
827                            .map(|f| format!("{} {}", f.key, f.value))
828                            .collect()
829                    })
830                    .unwrap_or_default();
831                let archive: BTreeSet<String> = crate::core::memory_lifecycle::list_archives(root)
832                    .iter()
833                    .flat_map(|path| {
834                        crate::core::memory_lifecycle::restore_archive(
835                            root,
836                            &path.to_string_lossy(),
837                        )
838                        .expect("own archive restores")
839                    })
840                    .map(|f| format!("{} {}", f.key, f.value))
841                    .collect();
842                let shared: BTreeSet<String> = SharedContext::for_project(root)
843                    .and_then(|store| store.get_recent(usize::MAX))
844                    .expect("shared memory")
845                    .into_iter()
846                    .map(|entry| entry.content)
847                    .collect();
848                let sessions: BTreeSet<String> =
849                    SessionState::load_recent_for_project_root(root, usize::MAX)
850                        .into_iter()
851                        .filter_map(|session| session.task.map(|task| task.description))
852                        .map(|value| {
853                            let key = KEYS
854                                .iter()
855                                .find(|key| value.ends_with(&format!("-{key}")))
856                                .expect("task names its key");
857                            format!("{key} {value}")
858                        })
859                        .collect();
860                let registry: BTreeSet<String> = AgentRegistry::new()
861                    .receive_shared_knowledge(root, "partition-reader")
862                    .expect("shared knowledge")
863                    .into_iter()
864                    .map(|fact| fact.text.replacen('=', " ", 1))
865                    .collect();
866                vec![
867                    ("knowledge", knowledge),
868                    ("archive", archive),
869                    ("shared memory", shared),
870                    ("sessions", sessions),
871                    ("shared knowledge", registry),
872                ]
873            })
874        }
875
876        /// I02/C01: writers of two projects start together (one barrier) and write
877        /// the same fact keys into one data directory through knowledge, archive,
878        /// shared memory, sessions and shared agent knowledge. Every acknowledged
879        /// write is kept, each in its own project only.
880        #[test]
881        fn concurrent_writes_into_two_projects_keep_every_write_in_its_own_partition() {
882            let _data = crate::core::data_dir::isolated_data_dir();
883            let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
884            let dir = tempfile::tempdir().unwrap();
885            let projects = [("p1", project(&dir, "p1")), ("p2", project(&dir, "p2"))];
886            let start = Arc::new(Barrier::new(projects.len() * KEYS.len()));
887            let start = &start;
888            let writers: Vec<_> = projects
889                .iter()
890                .flat_map(|(name, root)| {
891                    KEYS.iter().map(move |key| {
892                        let (start, root) = (Arc::clone(start), root.clone());
893                        let value = format!("canary-{name}-{key}");
894                        std::thread::spawn(move || {
895                            start.wait();
896                            write_everywhere(&root, key, &value);
897                        })
898                    })
899                })
900                .collect();
901            for writer in writers {
902                writer.join().expect("writer acknowledged every write");
903            }
904
905            for (name, root) in &projects {
906                let expected: BTreeSet<String> = KEYS
907                    .iter()
908                    .map(|key| format!("{key} canary-{name}-{key}"))
909                    .collect();
910                for (store, held) in partition_contents(root) {
911                    assert_eq!(held, expected, "{store} of {name}");
912                }
913            }
914        }
915    }
916
917    #[test]
918    fn put_and_get_round_trip() {
919        let context = store("round-trip");
920        let id = context
921            .put("Use cargo test --lib before commit", "codex", "fact")
922            .unwrap();
923        let entries = context.get_relevant("cargo commit", 10).unwrap();
924        assert_eq!(entries.len(), 1);
925        assert_eq!(entries[0].id, id);
926        assert_eq!(entries[0].agent, "codex");
927        assert_eq!(entries[0].access_count, 1);
928    }
929
930    #[test]
931    fn duplicate_content_updates_in_place() {
932        let context = store("dedup");
933        let first = context
934            .put("The parser needs UTF-8 input", "claude", "fact")
935            .unwrap();
936        let second = context
937            .put("The parser needs UTF-8 input", "codex", "decision")
938            .unwrap();
939        assert_eq!(first, second);
940        let stats = context.stats().unwrap();
941        assert_eq!(stats.total_entries, 1);
942        assert_eq!(stats.unique_agents, 1);
943        assert_eq!(context.get_recent(1).unwrap()[0].category, "decision");
944    }
945
946    #[test]
947    fn bm25_prefers_more_relevant_entries() {
948        let context = store("bm25");
949        context
950            .put("SQLite migration preserves agent memory", "claude", "fact")
951            .unwrap();
952        context
953            .put(
954                "Agent memory migration migration migration is complete",
955                "cursor",
956                "fact",
957            )
958            .unwrap();
959        context
960            .put("Rendering uses SVG sprites", "codex", "pattern")
961            .unwrap();
962        let entries = context.get_relevant("agent memory migration", 2).unwrap();
963        assert_eq!(entries[0].agent, "cursor");
964        assert_eq!(entries.len(), 2);
965    }
966
967    #[test]
968    fn prune_removes_expired_and_excess_entries() {
969        let context = store("prune");
970        context.put("old", "claude", "fact").unwrap();
971        context.put("new one", "codex", "fact").unwrap();
972        context.put("new two", "cursor", "fact").unwrap();
973        let mut entries = context.load().unwrap();
974        entries
975            .iter_mut()
976            .find(|entry| entry.content == "old")
977            .unwrap()
978            .last_accessed = 0;
979        context.save(&entries).unwrap();
980        // An hour, not a second: a slow runner must not age the fresh entries
981        // out. "old" expires by age, and one fresh entry goes to the cap.
982        assert_eq!(context.prune(3600, 1).unwrap(), 2);
983        assert_eq!(context.stats().unwrap().total_entries, 1);
984    }
985
986    #[test]
987    fn verify_fact_records_timestamp_and_count() {
988        let context = store("verify");
989        let id = context
990            .put("Cargo checks are required", "codex", "fact")
991            .unwrap();
992
993        context.verify_fact(&id).unwrap();
994        context.verify_fact(&id).unwrap();
995
996        let entry = context.get_recent(1).unwrap().pop().unwrap();
997        assert_eq!(entry.verification_count, 2);
998        assert!(entry.last_verified.is_some());
999    }
1000
1001    #[test]
1002    fn prune_stale_removes_old_unverified_facts() {
1003        let context = store("stale");
1004        context.put("outdated command", "codex", "fact").unwrap();
1005        context.put("current command", "codex", "fact").unwrap();
1006        let mut entries = context.load().unwrap();
1007        entries[0].timestamp = unix_timestamp().saturating_sub(2 * SECONDS_PER_DAY);
1008        entries[1].last_verified = Some(unix_timestamp());
1009        context.save(&entries).unwrap();
1010
1011        assert_eq!(context.prune_stale(1).unwrap(), 1);
1012        assert_eq!(
1013            context.get_recent(10).unwrap()[0].content,
1014            "current command"
1015        );
1016    }
1017
1018    #[test]
1019    fn get_best_prioritizes_high_quality_facts() {
1020        let context = store("best");
1021        context
1022            .put("cargo test validates changes", "claude", "fact")
1023            .unwrap();
1024        context
1025            .put("cargo test captures regressions", "codex", "fact")
1026            .unwrap();
1027        let mut entries = context.load().unwrap();
1028        entries[0].confidence = 0.4;
1029        entries[0].outcome_correlation = 0.5;
1030        entries[1].confidence = 0.9;
1031        entries[1].outcome_correlation = 0.9;
1032        context.save(&entries).unwrap();
1033
1034        let best = context.get_best("cargo test", 2).unwrap();
1035        assert_eq!(best[0].agent, "codex");
1036    }
1037
1038    #[test]
1039    fn recording_outcomes_updates_correlation_with_ema() {
1040        let context = store("outcomes");
1041        let id = context.put("test outcome", "codex", "fact").unwrap();
1042
1043        context.record_fact_outcome(&id, true).unwrap();
1044        let positive = context
1045            .get_recent(1)
1046            .unwrap()
1047            .pop()
1048            .unwrap()
1049            .outcome_correlation;
1050        context.record_fact_outcome(&id, false).unwrap();
1051        let mixed = context
1052            .get_recent(1)
1053            .unwrap()
1054            .pop()
1055            .unwrap()
1056            .outcome_correlation;
1057
1058        assert!((positive - 0.2).abs() < f32::EPSILON);
1059        assert!(mixed < positive);
1060    }
1061
1062    #[test]
1063    fn legacy_jsonl_entries_receive_provenance_defaults() {
1064        let context = store("legacy");
1065        fs::write(
1066            context.path(),
1067            r#"{"id":"legacy","content":"legacy fact","agent":"cursor","timestamp":7,"category":"fact","confidence":1.0,"access_count":0,"last_accessed":7}"#,
1068        )
1069        .unwrap();
1070
1071        let entry = context.get_recent(1).unwrap().pop().unwrap();
1072        assert_eq!(entry.confidence, 1.0);
1073        assert_eq!(entry.created_by, "cursor");
1074        assert_eq!(entry.last_verified, None);
1075        assert_eq!(entry.verification_count, 0);
1076        assert_eq!(entry.outcome_correlation, 0.0);
1077        assert_eq!(entry.stale_after_days, None);
1078        assert_eq!(entry.superseded_by, None);
1079    }
1080
1081    #[test]
1082    fn superseding_and_negative_pruning_track_quality() {
1083        let context = store("supersede");
1084        let old = context.put("old guidance", "codex", "fact").unwrap();
1085        let new = context.put("new guidance", "codex", "fact").unwrap();
1086        context.supersede(&old, &new).unwrap();
1087        context.record_fact_outcome(&old, false).unwrap();
1088        context.record_fact_outcome(&old, false).unwrap();
1089
1090        let entries = context.get_recent(2).unwrap();
1091        let old_entry = entries
1092            .iter()
1093            .find(|e| e.content == "old guidance")
1094            .unwrap();
1095        assert_eq!(old_entry.superseded_by, Some(new));
1096        assert_eq!(context.prune_negative().unwrap(), 1);
1097    }
1098}