Skip to main content

lean_ctx/core/knowledge/
core.rs

1use chrono::Utc;
2
3use super::ranking::{
4    build_knowledge_index, fact_version_id_v1, hash_project_root, string_similarity,
5};
6use super::types::{
7    AdmissionResult, Contradiction, ContradictionSeverity, KnowledgeArchetype, KnowledgeFact,
8    ProjectKnowledge, ProjectPattern,
9};
10use crate::core::memory_boundary::FactPrivacy;
11use crate::core::memory_policy::MemoryPolicy;
12
13impl ProjectKnowledge {
14    pub fn run_memory_lifecycle(
15        &mut self,
16        policy: &MemoryPolicy,
17    ) -> Result<crate::core::memory_lifecycle::LifecycleReport, String> {
18        let cfg = crate::core::memory_lifecycle::LifecycleConfig::from_policy(policy);
19        let report = crate::core::memory_lifecycle::run_lifecycle(&mut self.facts, &cfg);
20        if report.is_ok() {
21            self.rebuild_index();
22        }
23        report
24    }
25
26    /// Cluster compaction (#971): collapse piles of low-value, mutually-similar
27    /// facts into recoverable digests, returning the number of clusters
28    /// collapsed. Heavier than [`Self::run_memory_lifecycle`], so it runs only
29    /// from the background cognition loop (hourly), never on every write. The
30    /// originals are archived and rehydrate on recall — nothing is lost.
31    pub fn compact_low_value_clusters(&mut self, policy: &MemoryPolicy) -> u32 {
32        if !policy.compaction.enabled {
33            return 0;
34        }
35        let cfg = crate::core::memory_lifecycle::ClusterCompactionConfig {
36            min_cluster: policy.compaction.min_cluster,
37            similarity: policy.compaction.similarity,
38            max_confidence: policy.compaction.max_confidence,
39            max_confirmations: policy.compaction.max_confirmations,
40        };
41        let (collapsed, archived) =
42            crate::core::memory_lifecycle::compact_clusters(&mut self.facts, &cfg);
43        if !archived.is_empty() {
44            let _ = crate::core::memory_lifecycle::archive_facts(&archived);
45        }
46        self.rebuild_index();
47        collapsed as u32
48    }
49
50    pub fn new(project_root: &str) -> Self {
51        Self {
52            project_root: project_root.to_string(),
53            project_hash: hash_project_root(project_root),
54            facts: Vec::new(),
55            patterns: Vec::new(),
56            history: Vec::new(),
57            updated_at: Utc::now(),
58            judged_pairs: Vec::new(),
59            index: Default::default(),
60        }
61    }
62
63    /// Rebuilds the transient lookup tables after loading or changing facts.
64    /// The maps are intentionally excluded from JSON serialization.
65    pub fn rebuild_index(&mut self) {
66        self.index = build_knowledge_index(&self.facts);
67    }
68
69    pub fn check_contradiction(
70        &self,
71        category: &str,
72        key: &str,
73        new_value: &str,
74        policy: &MemoryPolicy,
75    ) -> Option<Contradiction> {
76        let existing = self
77            .facts
78            .iter()
79            .find(|f| f.category == category && f.key == key && f.is_current())?;
80
81        if existing.value.to_lowercase() == new_value.to_lowercase() {
82            return None;
83        }
84
85        let similarity = string_similarity(&existing.value, new_value);
86        if similarity > 0.8 {
87            return None;
88        }
89
90        let severity = if existing.confidence >= 0.9 && existing.confirmation_count >= 2 {
91            ContradictionSeverity::High
92        } else if existing.confidence >= policy.knowledge.contradiction_threshold {
93            ContradictionSeverity::Medium
94        } else {
95            ContradictionSeverity::Low
96        };
97
98        let resolution = match severity {
99            ContradictionSeverity::High => format!(
100                "High-confidence fact [{category}/{key}] changed: '{}' -> '{new_value}' (was confirmed {}x). Previous value archived.",
101                existing.value, existing.confirmation_count
102            ),
103            ContradictionSeverity::Medium => format!(
104                "Fact [{category}/{key}] updated: '{}' -> '{new_value}'",
105                existing.value
106            ),
107            ContradictionSeverity::Low => format!(
108                "Low-confidence fact [{category}/{key}] replaced: '{}' -> '{new_value}'",
109                existing.value
110            ),
111        };
112
113        Some(Contradiction {
114            existing_key: key.to_string(),
115            existing_value: existing.value.clone(),
116            new_value: new_value.to_string(),
117            category: category.to_string(),
118            severity,
119            resolution,
120        })
121    }
122
123    pub fn remember(
124        &mut self,
125        category: &str,
126        key: &str,
127        value: &str,
128        session_id: &str,
129        confidence: f32,
130        policy: &MemoryPolicy,
131    ) -> Option<Contradiction> {
132        // #1802: the store refuses machine-derived facts while auto-capture is
133        // off, whichever ingestion shape a producer uses. `add_fact` carries the
134        // same guard; between them no producer — present or future — can put an
135        // `auto:*` fact into the durable store behind the operator's back.
136        if super::persist::is_machine_derived(category, key)
137            && !super::persist::machine_derived_writes_allowed()
138        {
139            return None;
140        }
141        let contradiction = self.check_contradiction(category, key, value, policy);
142
143        if let Some(existing) = self
144            .facts
145            .iter_mut()
146            .find(|f| f.category == category && f.key == key && f.is_current())
147        {
148            let now = Utc::now();
149            let same_value_ci = existing.value.to_lowercase() == value.to_lowercase();
150            let similarity = string_similarity(&existing.value, value);
151
152            if existing.value == value || same_value_ci || similarity > 0.8 {
153                existing.last_confirmed = now;
154                existing.source_session = session_id.to_string();
155                existing.confidence = f32::midpoint(existing.confidence, confidence);
156                existing.confirmation_count += 1;
157                existing.revision_count += 1;
158
159                if existing.value != value && similarity > 0.8 && value.len() > existing.value.len()
160                {
161                    existing.value = value.to_string();
162                }
163            } else {
164                let superseded = fact_version_id_v1(existing);
165                let next_revision = existing.revision_count + 1;
166                existing.valid_until = Some(now);
167                existing.valid_from = existing.valid_from.or(Some(existing.created_at));
168
169                self.facts.push(KnowledgeFact {
170                    category: category.to_string(),
171                    key: key.to_string(),
172                    value: value.to_string(),
173                    source_session: session_id.to_string(),
174                    confidence,
175                    created_at: now,
176                    last_confirmed: now,
177                    retrieval_count: 0,
178                    last_retrieved: None,
179                    valid_from: Some(now),
180                    valid_until: None,
181                    supersedes: Some(superseded),
182                    confirmation_count: 1,
183                    feedback_up: 0,
184                    feedback_down: 0,
185                    last_feedback: None,
186                    privacy: FactPrivacy::default(),
187                    sensitivity: crate::core::sensitivity::classify_content(value),
188                    imported_from: None,
189                    archetype: KnowledgeArchetype::infer_from_category(category),
190                    fidelity: None,
191                    revision_count: next_revision,
192                });
193            }
194        } else {
195            let now = Utc::now();
196            self.facts.push(KnowledgeFact {
197                category: category.to_string(),
198                key: key.to_string(),
199                value: value.to_string(),
200                source_session: session_id.to_string(),
201                confidence,
202                created_at: now,
203                last_confirmed: now,
204                retrieval_count: 0,
205                last_retrieved: None,
206                valid_from: Some(now),
207                valid_until: None,
208                supersedes: None,
209                confirmation_count: 1,
210                feedback_up: 0,
211                feedback_down: 0,
212                last_feedback: None,
213                privacy: FactPrivacy::default(),
214                sensitivity: crate::core::sensitivity::classify_content(value),
215                imported_from: None,
216                archetype: KnowledgeArchetype::infer_from_category(category),
217                fidelity: None,
218                revision_count: 1,
219            });
220        }
221
222        // Run the lifecycle as soon as we exceed the configured budget.
223        // `run_lifecycle` sorts by importance and drains the excess back down to
224        // `max_facts` (archiving it), so this is self-limiting: the store settles
225        // at <= max_facts. The previous `* 2` guard let a project's facts grow to
226        // twice the cap before any eviction fired, which is why stores were
227        // observed sitting at 103% (206/200) with no reclamation.
228        if self.facts.len() > policy.knowledge.max_facts {
229            let _ = self.run_memory_lifecycle(policy);
230        }
231
232        self.updated_at = Utc::now();
233        self.rebuild_index();
234
235        let action = if contradiction.is_some() {
236            "contradict"
237        } else {
238            "remember"
239        };
240        crate::core::events::emit(crate::core::events::EventKind::KnowledgeUpdate {
241            category: category.to_string(),
242            key: key.to_string(),
243            action: action.to_string(),
244        });
245
246        contradiction
247    }
248
249    /// Write-time admission gate for the agent-facing `ctx_knowledge remember`
250    /// path (#970). Unlike [`Self::remember`] (which every internal restorer also
251    /// calls), this enforces the [`crate::core::memory_policy::AdmissionPolicy`]:
252    /// near-duplicates are merged instead of inserted, and low-salience noise is
253    /// kept out of the capped store — so eviction never has to drop a good fact to
254    /// make room for a paraphrase. Internal callers (archive rehydrate, cognition
255    /// auto-promotion) keep using [`Self::remember`] and are never gated.
256    pub fn remember_admitted(
257        &mut self,
258        category: &str,
259        key: &str,
260        value: &str,
261        session_id: &str,
262        confidence: f32,
263        policy: &MemoryPolicy,
264    ) -> AdmissionResult {
265        let adm = &policy.admission;
266
267        // Admission only governs *new* facts. An existing (category,key) is a
268        // confirm/supersede the agent explicitly addressed — defer to remember().
269        let has_exact = self
270            .facts
271            .iter()
272            .any(|f| f.category == category && f.key == key && f.is_current());
273        if !adm.enabled || has_exact {
274            return AdmissionResult::Stored(
275                self.remember(category, key, value, session_id, confidence, policy),
276            );
277        }
278
279        // Salience floor: keep low-signal noise out of a capped store.
280        if adm.min_salience > 0 {
281            let salience = crate::core::memory_salience::text_salience(value);
282            if salience < adm.min_salience {
283                return AdmissionResult::RejectedLowSalience {
284                    salience,
285                    floor: adm.min_salience,
286                };
287            }
288        }
289
290        // Cross-key near-duplicate auto-merge within the same category.
291        if adm.auto_merge_similarity > 0.0
292            && let Some(merged) = self.merge_near_duplicate(
293                category,
294                value,
295                session_id,
296                confidence,
297                adm.auto_merge_similarity,
298            )
299        {
300            return merged;
301        }
302
303        AdmissionResult::Stored(self.remember(category, key, value, session_id, confidence, policy))
304    }
305
306    /// Find the best same-category, different-key, *current* near-duplicate of
307    /// `value` at/above `threshold` and merge into it (confirmation bump,
308    /// confidence midpoint, keep the longer/more-complete value). Returns the
309    /// merge outcome, or `None` when nothing qualifies. Deterministic: ties
310    /// resolve to the earliest-inserted fact (stable scan, strict `>`).
311    fn merge_near_duplicate(
312        &mut self,
313        category: &str,
314        value: &str,
315        session_id: &str,
316        confidence: f32,
317        threshold: f32,
318    ) -> Option<AdmissionResult> {
319        let mut best: Option<(usize, f32)> = None;
320        for (i, f) in self.facts.iter().enumerate() {
321            if !f.is_current() || f.category != category {
322                continue;
323            }
324            let sim = string_similarity(value, &f.value);
325            if sim >= threshold && best.is_none_or(|(_, bs)| sim > bs) {
326                best = Some((i, sim));
327            }
328        }
329        let (idx, _) = best?;
330        let now = Utc::now();
331        let f = &mut self.facts[idx];
332        f.last_confirmed = now;
333        f.source_session = session_id.to_string();
334        f.confidence = f32::midpoint(f.confidence, confidence);
335        f.confirmation_count += 1;
336        f.revision_count += 1;
337        if value.len() > f.value.len() {
338            f.value = value.to_string();
339        }
340        let result = AdmissionResult::Merged {
341            category: f.category.clone(),
342            key: f.key.clone(),
343            confirmations: f.confirmation_count,
344            value: f.value.clone(),
345        };
346        self.rebuild_index();
347        Some(result)
348    }
349
350    pub fn add_pattern(
351        &mut self,
352        pattern_type: &str,
353        description: &str,
354        examples: Vec<String>,
355        session_id: &str,
356        policy: &MemoryPolicy,
357    ) {
358        if let Some(existing) = self
359            .patterns
360            .iter_mut()
361            .find(|p| p.pattern_type == pattern_type && p.description == description)
362        {
363            for ex in &examples {
364                if !existing.examples.contains(ex) {
365                    existing.examples.push(ex.clone());
366                }
367            }
368            return;
369        }
370
371        self.patterns.push(ProjectPattern {
372            pattern_type: pattern_type.to_string(),
373            description: description.to_string(),
374            examples,
375            source_session: session_id.to_string(),
376            created_at: Utc::now(),
377        });
378
379        // Lossless capacity reclaim (#995): keep the newest patterns and archive
380        // the rest. The previous `truncate` kept the *oldest* patterns (it dropped
381        // the just-pushed one once at the cap) and lost them permanently.
382        if let Err(error) = crate::core::memory_capacity::reclaim_store(
383            crate::core::memory_archive::MemoryStore::Patterns,
384            Some(&self.project_hash),
385            &mut self.patterns,
386            policy.knowledge.max_patterns,
387            policy.lifecycle.reclaim_headroom_pct,
388            policy.lifecycle.reclaim_enabled,
389            |a, b| {
390                b.created_at
391                    .cmp(&a.created_at)
392                    .then_with(|| a.pattern_type.cmp(&b.pattern_type))
393                    .then_with(|| a.description.cmp(&b.description))
394            },
395        ) {
396            tracing::warn!(%error, "pattern capacity reclaim failed");
397        }
398        self.updated_at = Utc::now();
399    }
400
401    pub fn remove_fact(&mut self, category: &str, key: &str) -> bool {
402        let before = self.facts.len();
403        self.facts
404            .retain(|f| !(f.category == category && f.key == key));
405        let removed = self.facts.len() < before;
406        if removed {
407            self.updated_at = Utc::now();
408            self.rebuild_index();
409        }
410        removed
411    }
412}