Skip to main content

lean_ctx_ext/core/
semantic_cache.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Per-project similarity index over the files a session read.
3//!
4//! An entry is derived from ONE file: its path and the term frequencies of
5//! its text. It is a derived store like any index (G04, E3):
6//!
7//! - at the write the text passes storage admission (`StoreAdmission`); text
8//!   that is withheld or restricted leaves no entry, and the index records
9//!   the digest of the policy its entries were admitted under;
10//! - at the use ([`SemanticCacheIndex::find_similar`]) an index its store
11//!   loaded names a file only while the admitted rooted reader returns that
12//!   file NOW and its text still has the terms the entry was built from. A
13//!   file that is gone, outside the project, withheld, restricted or changed
14//!   is not named; its entry is refreshed when the file is read again.
15//!
16//! The reads of one `find_similar` call are bounded and not remembered
17//! beyond it.
18
19use std::collections::{HashMap, HashSet};
20use std::path::{Path, PathBuf};
21
22use serde::{Deserialize, Serialize};
23
24use crate::core::context_admission::stores::StoreAdmission;
25
26/// Tool identity the source of an entry is re-read for.
27const SOURCE_TOOL: &str = "ctx_read";
28/// Sources one `find_similar` call re-reads. Over it nothing more is named
29/// (fail closed): fewer hints, never an unchecked one.
30const MAX_SOURCE_READS: usize = 16;
31
32/// Recompute global IDF after this many mutations; searches refresh IDF when `idf_dirty`.
33const IDF_REBUILD_BATCH: u32 = 100;
34/// Hard cap on cached entries. Matches the search cap so the index stays bounded and
35/// never grows past what `find_similar` will actually search (previously the structure
36/// grew one entry per distinct file ever read, with no eviction).
37const MAX_SEMANTIC_ENTRIES: usize = 200;
38
39#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct SemanticCacheEntry {
41    pub path: String,
42    pub tfidf_vector: Vec<(String, f64)>,
43    pub token_count: usize,
44    pub access_count: u32,
45    pub last_session: String,
46}
47
48#[derive(Debug, Clone, Serialize, Deserialize, Default)]
49pub struct SemanticCacheIndex {
50    pub entries: Vec<SemanticCacheEntry>,
51    pub idf: HashMap<String, f64>,
52    pub total_docs: usize,
53    /// Documents containing each term (unique terms per entry).
54    #[serde(default)]
55    pub term_document_freq: HashMap<String, usize>,
56    #[serde(default)]
57    idf_dirty: bool,
58    #[serde(default)]
59    mutations_since_idf_rebuild: u32,
60    /// Hex digest of the gateway policy every entry was admitted under. An
61    /// index of another policy — or of none, written before admission
62    /// existed — is not handed out ([`Self::load`]).
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    admission_policy: Option<String>,
65    /// Set for an index its store loaded for a project: its entries are asked
66    /// again before they are named. Resident only.
67    #[serde(skip)]
68    source_root: Option<PathBuf>,
69}
70
71/// The current gateway policy as a snapshot that is not observed: a caller
72/// may hold a cache lock, and observing a change drops resident stores.
73fn store_admission() -> StoreAdmission {
74    StoreAdmission::with_policy(
75        crate::core::context_admission::AdmissionPolicy::from_config(
76            &crate::core::config::Config::load_arc(),
77        ),
78    )
79}
80
81impl SemanticCacheIndex {
82    /// Index `content` of `path`. Only text storage admission keeps enters:
83    /// a withheld or restricted source leaves no entry (an earlier one of the
84    /// same path is dropped), and entries admitted under another policy are
85    /// dropped before the first write under this one.
86    pub fn add_file(&mut self, path: &str, content: &str, session_id: &str) {
87        let admission = store_admission();
88        if self.admission_policy.as_deref() != Some(admission.digest()) {
89            self.entries.clear();
90            self.term_document_freq.clear();
91            self.idf.clear();
92            self.admission_policy = Some(admission.digest().to_owned());
93        }
94        let Some(admitted) = admission.admit(content, Path::new(path), None) else {
95            if let Some(position) = self.entries.iter().position(|e| e.path == path) {
96                let dropped = self.entries.swap_remove(position);
97                remove_doc_terms(&mut self.term_document_freq, &dropped.tfidf_vector);
98                self.total_docs = self.entries.len();
99                self.note_idf_mutation();
100            }
101            return;
102        };
103        let content = admitted.as_str();
104        let tf = compute_tf(content);
105        let token_count = content.split_whitespace().count();
106
107        if let Some(existing) = self.entries.iter_mut().find(|e| e.path == path) {
108            remove_doc_terms(&mut self.term_document_freq, &existing.tfidf_vector);
109            existing.tfidf_vector = tf.iter().map(|(k, v)| (k.clone(), *v)).collect();
110            existing.token_count = token_count;
111            existing.access_count += 1;
112            existing.last_session = session_id.to_string();
113            add_doc_terms(&mut self.term_document_freq, &existing.tfidf_vector);
114        } else {
115            if self.entries.len() >= MAX_SEMANTIC_ENTRIES {
116                // Evict the lowest-access_count entry to bound the index. Decrement its
117                // terms from the DF map via the existing helper so IDF stays correct.
118                if let Some(victim_idx) = self
119                    .entries
120                    .iter()
121                    .enumerate()
122                    .min_by_key(|(_, e)| e.access_count)
123                    .map(|(i, _)| i)
124                {
125                    let victim = self.entries.swap_remove(victim_idx);
126                    remove_doc_terms(&mut self.term_document_freq, &victim.tfidf_vector);
127                }
128            }
129            let tf_vec: Vec<(String, f64)> = tf.iter().map(|(k, v)| (k.clone(), *v)).collect();
130            add_doc_terms(&mut self.term_document_freq, &tf_vec);
131            self.entries.push(SemanticCacheEntry {
132                path: path.to_string(),
133                tfidf_vector: tf_vec,
134                token_count,
135                access_count: 1,
136                last_session: session_id.to_string(),
137            });
138        }
139
140        self.total_docs = self.entries.len();
141        self.note_idf_mutation();
142    }
143
144    fn note_idf_mutation(&mut self) {
145        self.idf_dirty = true;
146        self.mutations_since_idf_rebuild = self.mutations_since_idf_rebuild.saturating_add(1);
147        if self.mutations_since_idf_rebuild >= IDF_REBUILD_BATCH {
148            self.recompute_idf_from_df();
149            self.idf_dirty = false;
150            self.mutations_since_idf_rebuild = 0;
151        }
152    }
153
154    fn recompute_idf_from_df(&mut self) {
155        self.idf.clear();
156        let n = self.total_docs as f64;
157        if n <= 0.0 {
158            return;
159        }
160        for (term, count) in &self.term_document_freq {
161            let idf = (n / (*count as f64 + 1.0)).ln() + 1.0;
162            self.idf.insert(term.clone(), idf);
163        }
164    }
165
166    fn rebuild_df_from_entries(&mut self) {
167        self.term_document_freq.clear();
168        for entry in &self.entries {
169            add_doc_terms(&mut self.term_document_freq, &entry.tfidf_vector);
170        }
171    }
172
173    fn repair_after_deserialize(&mut self) {
174        self.total_docs = self.entries.len();
175        if self.term_document_freq.is_empty() && !self.entries.is_empty() {
176            self.rebuild_df_from_entries();
177            self.idf_dirty = true;
178        }
179    }
180
181    fn ensure_idf_for_search(&mut self) {
182        if self.idf_dirty {
183            self.recompute_idf_from_df();
184            self.idf_dirty = false;
185            self.mutations_since_idf_rebuild = 0;
186        }
187    }
188
189    pub fn find_similar(&mut self, content: &str, threshold: f64) -> Vec<(String, f64)> {
190        if self.entries.len() > MAX_SEMANTIC_ENTRIES {
191            return Vec::new();
192        }
193
194        self.ensure_idf_for_search();
195
196        let query_tf = compute_tf(content);
197        let query_vec = self.tfidf_vector(&query_tf);
198
199        let mut results: Vec<(String, f64)> = self
200            .entries
201            .iter()
202            .filter_map(|entry| {
203                let entry_vec = self.tfidf_vector_from_stored(&entry.tfidf_vector);
204                let sim = cosine_similarity(&query_vec, &entry_vec);
205                if sim >= threshold {
206                    Some((entry.path.clone(), sim))
207                } else {
208                    None
209                }
210            })
211            .collect();
212
213        results.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
214        let Some(root) = self.source_root.as_deref() else {
215            // A view built in the running call, never handed out by the store.
216            return results;
217        };
218        // The gate of this call: best match first, each source read once.
219        let mut reads = 0usize;
220        let mut remaining = crate::core::limits::max_read_bytes();
221        let before = results.len();
222        results.retain(|(path, _)| {
223            if reads >= MAX_SOURCE_READS {
224                return false;
225            }
226            reads += 1;
227            self.entries
228                .iter()
229                .find(|entry| &entry.path == path)
230                .is_some_and(|entry| still_derived(root, entry, &mut remaining))
231        });
232        if results.len() < before {
233            tracing::debug!(
234                "[semantic-cache] {} entr(y/ies) withheld: source no longer admitted",
235                before - results.len()
236            );
237        }
238        results
239    }
240
241    /// Paths ranked by access. Test-only: it has no product caller, and a
242    /// product use would have to gate its paths like [`Self::find_similar`].
243    #[cfg(test)]
244    pub fn suggest_warmup(&self, top_n: usize) -> Vec<String> {
245        let mut ranked: Vec<(&SemanticCacheEntry, f64)> = self
246            .entries
247            .iter()
248            .map(|e| {
249                let score = e.access_count as f64 * 0.6 + e.token_count as f64 * 0.0001;
250                (e, score)
251            })
252            .collect();
253
254        ranked.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
255
256        ranked
257            .into_iter()
258            .take(top_n)
259            .map(|(e, _)| e.path.clone())
260            .collect()
261    }
262
263    fn tfidf_vector(&self, tf: &HashMap<String, f64>) -> HashMap<String, f64> {
264        tf.iter()
265            .map(|(term, freq)| {
266                let idf = self.idf.get(term).copied().unwrap_or(1.0);
267                (term.clone(), freq * idf)
268            })
269            .collect()
270    }
271
272    fn tfidf_vector_from_stored(&self, stored: &[(String, f64)]) -> HashMap<String, f64> {
273        stored
274            .iter()
275            .map(|(term, freq)| {
276                let idf = self.idf.get(term).copied().unwrap_or(1.0);
277                (term.clone(), freq * idf)
278            })
279            .collect()
280    }
281
282    pub fn save(&self, project_root: &str) -> Result<(), String> {
283        let path = index_path(project_root);
284        if let Some(dir) = path.parent() {
285            std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
286        }
287        let json = serde_json::to_string(self).map_err(|e| e.to_string())?;
288        std::fs::write(&path, json).map_err(|e| e.to_string())
289    }
290
291    pub fn load(project_root: &str) -> Option<Self> {
292        let path = index_path(project_root);
293        let content = std::fs::read_to_string(&path)
294            .or_else(|_| {
295                let legacy = legacy_index_path(project_root);
296                if legacy == path {
297                    return Err(std::io::Error::new(
298                        std::io::ErrorKind::NotFound,
299                        "same path",
300                    ));
301                }
302                let data = std::fs::read_to_string(&legacy)?;
303                let _ = std::fs::copy(&legacy, &path);
304                Ok(data)
305            })
306            .ok()?;
307        let mut index: SemanticCacheIndex = serde_json::from_str(&content).ok()?;
308        // Only an index of the current policy is handed out. One written
309        // under another policy, or before admission existed (no digest), is
310        // left behind: its entries come back through admission as their
311        // files are read again.
312        if index.admission_policy.as_deref() != Some(store_admission().digest()) {
313            return None;
314        }
315        index.repair_after_deserialize();
316        index.source_root = Some(PathBuf::from(project_root));
317        Some(index)
318    }
319
320    pub fn load_or_create(project_root: &str) -> Self {
321        Self::load(project_root).unwrap_or_else(|| Self {
322            source_root: Some(PathBuf::from(project_root)),
323            ..Self::default()
324        })
325    }
326}
327
328/// Whether `entry` is still what its source yields: the admitted rooted
329/// reader returns the file now (path jail, role, project policy, gateway,
330/// decided on the original bytes), the original may be kept in a derived
331/// store, and its text has exactly the terms the entry was built from.
332fn still_derived(root: &Path, entry: &SemanticCacheEntry, remaining: &mut usize) -> bool {
333    let path = root.join(&entry.path);
334    let (Some(path), Some(root)) = (path.to_str(), root.to_str()) else {
335        return false;
336    };
337    let read = crate::core::admitted_sources::read(path, root, SOURCE_TOOL, remaining);
338    read.storable().is_some_and(|current| {
339        let terms = compute_tf(current);
340        terms.len() == entry.tfidf_vector.len()
341            && entry
342                .tfidf_vector
343                .iter()
344                .all(|(term, frequency)| terms.get(term) == Some(frequency))
345    })
346}
347
348fn remove_doc_terms(df: &mut HashMap<String, usize>, tf_vec: &[(String, f64)]) {
349    let unique: HashSet<&str> = tf_vec.iter().map(|(k, _)| k.as_str()).collect();
350    for term in unique {
351        if let Some(c) = df.get_mut(term) {
352            *c = c.saturating_sub(1);
353            if *c == 0 {
354                df.remove(term);
355            }
356        }
357    }
358}
359
360fn add_doc_terms(df: &mut HashMap<String, usize>, tf_vec: &[(String, f64)]) {
361    let unique: HashSet<&str> = tf_vec.iter().map(|(k, _)| k.as_str()).collect();
362    for term in unique {
363        *df.entry(term.to_string()).or_default() += 1;
364    }
365}
366
367fn compute_tf(content: &str) -> HashMap<String, f64> {
368    let mut counts: HashMap<String, usize> = HashMap::new();
369    let mut total = 0usize;
370
371    for word in content.split(|c: char| !c.is_alphanumeric() && c != '_') {
372        let w = word.to_lowercase();
373        if w.len() >= 2 {
374            *counts.entry(w).or_default() += 1;
375            total += 1;
376        }
377    }
378
379    if total == 0 {
380        return HashMap::new();
381    }
382
383    counts
384        .into_iter()
385        .map(|(term, count)| (term, count as f64 / total as f64))
386        .collect()
387}
388
389fn cosine_similarity(a: &HashMap<String, f64>, b: &HashMap<String, f64>) -> f64 {
390    let mut dot = 0.0f64;
391    let mut norm_a = 0.0f64;
392    let mut norm_b = 0.0f64;
393
394    for (term, val) in a {
395        norm_a += val * val;
396        if let Some(bval) = b.get(term) {
397            dot += val * bval;
398        }
399    }
400    for val in b.values() {
401        norm_b += val * val;
402    }
403
404    let denom = norm_a.sqrt() * norm_b.sqrt();
405    if denom < 1e-10 {
406        return 0.0;
407    }
408    dot / denom
409}
410
411fn index_path(project_root: &str) -> PathBuf {
412    let hash = crate::core::project_hash::hash_project_root(project_root);
413    crate::core::paths::cache_dir()
414        .unwrap_or_default()
415        .join("semantic_cache")
416        .join(format!("{hash}.json"))
417}
418
419fn legacy_index_path(project_root: &str) -> PathBuf {
420    use md5::{Digest, Md5};
421    let mut hasher = Md5::new();
422    hasher.update(project_root.as_bytes());
423    let hash = crate::core::agent_identity::hex_encode(&hasher.finalize());
424    crate::core::paths::cache_dir()
425        .unwrap_or_default()
426        .join("semantic_cache")
427        .join(format!("{hash}.json"))
428}
429
430#[cfg(test)]
431pub mod tests {
432    use super::*;
433
434    #[test]
435    fn compute_tf_basic() {
436        let tf = compute_tf("fn handle_request request response handle");
437        assert!(tf.contains_key("handle"));
438        assert!(tf.contains_key("request"));
439        assert!(tf["handle"] > 0.0);
440    }
441
442    #[test]
443    fn cosine_identical() {
444        let mut a = HashMap::new();
445        a.insert("hello".to_string(), 1.0);
446        a.insert("world".to_string(), 0.5);
447        let sim = cosine_similarity(&a, &a);
448        assert!((sim - 1.0).abs() < 0.001);
449    }
450
451    #[test]
452    fn cosine_orthogonal() {
453        let mut a = HashMap::new();
454        a.insert("hello".to_string(), 1.0);
455        let mut b = HashMap::new();
456        b.insert("world".to_string(), 1.0);
457        let sim = cosine_similarity(&a, &b);
458        assert!(sim.abs() < 0.001);
459    }
460
461    #[test]
462    fn add_and_find_similar() {
463        let mut index = SemanticCacheIndex::default();
464        index.add_file(
465            "auth.rs",
466            "fn validate_token check jwt expiry auth login",
467            "s1",
468        );
469        index.add_file(
470            "db.rs",
471            "fn connect_database pool query insert delete",
472            "s1",
473        );
474
475        let results = index.find_similar("validate auth token jwt", 0.1);
476        assert!(!results.is_empty(), "`results` is empty");
477        assert_eq!(results[0].0, "auth.rs");
478    }
479
480    #[test]
481    fn warmup_suggestions() {
482        let mut index = SemanticCacheIndex::default();
483        index.add_file("hot.rs", "frequently accessed file", "s1");
484        index.entries[0].access_count = 50;
485        index.add_file("cold.rs", "rarely used", "s1");
486
487        let warmup = index.suggest_warmup(1);
488        assert_eq!(warmup.len(), 1);
489        assert_eq!(warmup[0], "hot.rs");
490    }
491
492    /// G04/E3: an index its store loaded names a similar file only while the
493    /// admitted reader still returns the text its entry was built from, and
494    /// restricted text never becomes an entry.
495    #[test]
496    fn a_loaded_index_names_a_file_only_while_its_source_admits_it() {
497        let _data = crate::core::data_dir::isolated_data_dir();
498        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
499        let project = tempfile::tempdir().expect("project");
500        let root = project.path().canonicalize().expect("canonical root");
501        let root_text = root.to_str().expect("utf-8 root");
502        let body = "fn settle_invoice reconciliation ledger posting balance\n";
503        let file = |name: &str| root.join(name).to_str().expect("utf-8 path").to_owned();
504        for name in ["billing.rs", "ledger.rs"] {
505            std::fs::write(root.join(name), body).expect("source");
506        }
507        let mut index = SemanticCacheIndex::load_or_create(root_text);
508        index.add_file(&file("billing.rs"), body, "s1");
509        index.add_file(&file("ledger.rs"), body, "s1");
510        index.add_file(
511            &file("plan.rs"),
512            &format!("*** TOP SECRET ***\n{body}"),
513            "s1",
514        );
515        assert!(
516            index
517                .entries
518                .iter()
519                .all(|entry| !entry.path.ends_with("plan.rs"))
520        );
521        index.save(root_text).expect("persisted");
522
523        let named = || -> Vec<String> {
524            SemanticCacheIndex::load(root_text)
525                .expect("index of the current policy")
526                .find_similar(body, 0.5)
527                .into_iter()
528                .map(|(path, _)| path)
529                .collect()
530        };
531        assert_eq!(named().len(), 2);
532
533        // Rewritten, then deleted: the entry no longer is what the source yields.
534        std::fs::write(root.join("billing.rs"), "fn unrelated() {}\n").expect("rewrite");
535        assert_eq!(named(), [file("ledger.rs")]);
536        std::fs::remove_file(root.join("ledger.rs")).expect("delete");
537        assert!(named().is_empty());
538    }
539}