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