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