Skip to main content

better_ctx/core/
knowledge.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use std::path::PathBuf;
4
5const MAX_FACTS: usize = 200;
6const MAX_PATTERNS: usize = 50;
7const MAX_HISTORY: usize = 100;
8const CONTRADICTION_THRESHOLD: f32 = 0.5;
9
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct ProjectKnowledge {
12    pub project_root: String,
13    pub project_hash: String,
14    pub facts: Vec<KnowledgeFact>,
15    pub patterns: Vec<ProjectPattern>,
16    pub history: Vec<ConsolidatedInsight>,
17    pub updated_at: DateTime<Utc>,
18}
19
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct KnowledgeFact {
22    pub category: String,
23    pub key: String,
24    pub value: String,
25    pub source_session: String,
26    pub confidence: f32,
27    pub created_at: DateTime<Utc>,
28    pub last_confirmed: DateTime<Utc>,
29    #[serde(default)]
30    pub valid_from: Option<DateTime<Utc>>,
31    #[serde(default)]
32    pub valid_until: Option<DateTime<Utc>>,
33    #[serde(default)]
34    pub supersedes: Option<String>,
35    #[serde(default)]
36    pub confirmation_count: u32,
37}
38
39#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct Contradiction {
41    pub existing_key: String,
42    pub existing_value: String,
43    pub new_value: String,
44    pub category: String,
45    pub severity: ContradictionSeverity,
46    pub resolution: String,
47}
48
49#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
50pub enum ContradictionSeverity {
51    Low,
52    Medium,
53    High,
54}
55
56#[derive(Debug, Clone, Serialize, Deserialize)]
57pub struct ProjectPattern {
58    pub pattern_type: String,
59    pub description: String,
60    pub examples: Vec<String>,
61    pub source_session: String,
62    pub created_at: DateTime<Utc>,
63}
64
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct ConsolidatedInsight {
67    pub summary: String,
68    pub from_sessions: Vec<String>,
69    pub timestamp: DateTime<Utc>,
70}
71
72impl ProjectKnowledge {
73    pub fn new(project_root: &str) -> Self {
74        Self {
75            project_root: project_root.to_string(),
76            project_hash: hash_project_root(project_root),
77            facts: Vec::new(),
78            patterns: Vec::new(),
79            history: Vec::new(),
80            updated_at: Utc::now(),
81        }
82    }
83
84    pub fn check_contradiction(
85        &self,
86        category: &str,
87        key: &str,
88        new_value: &str,
89    ) -> Option<Contradiction> {
90        let existing = self
91            .facts
92            .iter()
93            .find(|f| f.category == category && f.key == key && f.is_current())?;
94
95        if existing.value.to_lowercase() == new_value.to_lowercase() {
96            return None;
97        }
98
99        let similarity = string_similarity(&existing.value, new_value);
100        if similarity > 0.8 {
101            return None;
102        }
103
104        let severity = if existing.confidence >= 0.9 && existing.confirmation_count >= 2 {
105            ContradictionSeverity::High
106        } else if existing.confidence >= CONTRADICTION_THRESHOLD {
107            ContradictionSeverity::Medium
108        } else {
109            ContradictionSeverity::Low
110        };
111
112        let resolution = match severity {
113            ContradictionSeverity::High => format!(
114                "High-confidence fact [{category}/{key}] changed: '{}' -> '{new_value}' (was confirmed {}x). Previous value archived.",
115                existing.value, existing.confirmation_count
116            ),
117            ContradictionSeverity::Medium => format!(
118                "Fact [{category}/{key}] updated: '{}' -> '{new_value}'",
119                existing.value
120            ),
121            ContradictionSeverity::Low => format!(
122                "Low-confidence fact [{category}/{key}] replaced: '{}' -> '{new_value}'",
123                existing.value
124            ),
125        };
126
127        Some(Contradiction {
128            existing_key: key.to_string(),
129            existing_value: existing.value.clone(),
130            new_value: new_value.to_string(),
131            category: category.to_string(),
132            severity,
133            resolution,
134        })
135    }
136
137    pub fn remember(
138        &mut self,
139        category: &str,
140        key: &str,
141        value: &str,
142        session_id: &str,
143        confidence: f32,
144    ) -> Option<Contradiction> {
145        let contradiction = self.check_contradiction(category, key, value);
146
147        if let Some(existing) = self
148            .facts
149            .iter_mut()
150            .find(|f| f.category == category && f.key == key && f.is_current())
151        {
152            if existing.value != value {
153                if existing.confidence >= 0.9 && existing.confirmation_count >= 2 {
154                    existing.valid_until = Some(Utc::now());
155                    let superseded_id = format!("{}/{}", existing.category, existing.key);
156                    let now = Utc::now();
157                    self.facts.push(KnowledgeFact {
158                        category: category.to_string(),
159                        key: key.to_string(),
160                        value: value.to_string(),
161                        source_session: session_id.to_string(),
162                        confidence,
163                        created_at: now,
164                        last_confirmed: now,
165                        valid_from: Some(now),
166                        valid_until: None,
167                        supersedes: Some(superseded_id),
168                        confirmation_count: 1,
169                    });
170                } else {
171                    existing.value = value.to_string();
172                    existing.confidence = confidence;
173                    existing.last_confirmed = Utc::now();
174                    existing.source_session = session_id.to_string();
175                    existing.valid_from = existing.valid_from.or(Some(existing.created_at));
176                    existing.confirmation_count = 1;
177                }
178            } else {
179                existing.last_confirmed = Utc::now();
180                existing.source_session = session_id.to_string();
181                existing.confidence = (existing.confidence + confidence) / 2.0;
182                existing.confirmation_count += 1;
183            }
184        } else {
185            let now = Utc::now();
186            self.facts.push(KnowledgeFact {
187                category: category.to_string(),
188                key: key.to_string(),
189                value: value.to_string(),
190                source_session: session_id.to_string(),
191                confidence,
192                created_at: now,
193                last_confirmed: now,
194                valid_from: Some(now),
195                valid_until: None,
196                supersedes: None,
197                confirmation_count: 1,
198            });
199        }
200
201        if self.facts.len() > MAX_FACTS {
202            self.facts
203                .sort_by(|a, b| b.last_confirmed.cmp(&a.last_confirmed));
204            self.facts.truncate(MAX_FACTS);
205        }
206
207        self.updated_at = Utc::now();
208        contradiction
209    }
210
211    pub fn recall(&self, query: &str) -> Vec<&KnowledgeFact> {
212        let q = query.to_lowercase();
213        let terms: Vec<&str> = q.split_whitespace().collect();
214
215        let mut results: Vec<(&KnowledgeFact, f32)> = self
216            .facts
217            .iter()
218            .filter(|f| f.is_current())
219            .filter_map(|f| {
220                let searchable = format!(
221                    "{} {} {} {}",
222                    f.category.to_lowercase(),
223                    f.key.to_lowercase(),
224                    f.value.to_lowercase(),
225                    f.source_session
226                );
227                let match_count = terms.iter().filter(|t| searchable.contains(**t)).count();
228                if match_count > 0 {
229                    let relevance = (match_count as f32 / terms.len() as f32) * f.confidence;
230                    Some((f, relevance))
231                } else {
232                    None
233                }
234            })
235            .collect();
236
237        results.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
238        results.into_iter().map(|(f, _)| f).collect()
239    }
240
241    pub fn recall_by_category(&self, category: &str) -> Vec<&KnowledgeFact> {
242        self.facts
243            .iter()
244            .filter(|f| f.category == category && f.is_current())
245            .collect()
246    }
247
248    pub fn recall_at_time(&self, query: &str, at: DateTime<Utc>) -> Vec<&KnowledgeFact> {
249        let q = query.to_lowercase();
250        let terms: Vec<&str> = q.split_whitespace().collect();
251
252        let mut results: Vec<(&KnowledgeFact, f32)> = self
253            .facts
254            .iter()
255            .filter(|f| f.was_valid_at(at))
256            .filter_map(|f| {
257                let searchable = format!(
258                    "{} {} {}",
259                    f.category.to_lowercase(),
260                    f.key.to_lowercase(),
261                    f.value.to_lowercase(),
262                );
263                let match_count = terms.iter().filter(|t| searchable.contains(**t)).count();
264                if match_count > 0 {
265                    Some((f, match_count as f32 / terms.len() as f32))
266                } else {
267                    None
268                }
269            })
270            .collect();
271
272        results.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
273        results.into_iter().map(|(f, _)| f).collect()
274    }
275
276    pub fn timeline(&self, category: &str) -> Vec<&KnowledgeFact> {
277        let mut facts: Vec<&KnowledgeFact> = self
278            .facts
279            .iter()
280            .filter(|f| f.category == category)
281            .collect();
282        facts.sort_by(|a, b| a.created_at.cmp(&b.created_at));
283        facts
284    }
285
286    pub fn list_rooms(&self) -> Vec<(String, usize)> {
287        let mut categories: std::collections::BTreeMap<String, usize> =
288            std::collections::BTreeMap::new();
289        for f in &self.facts {
290            if f.is_current() {
291                *categories.entry(f.category.clone()).or_insert(0) += 1;
292            }
293        }
294        categories.into_iter().collect()
295    }
296
297    pub fn add_pattern(
298        &mut self,
299        pattern_type: &str,
300        description: &str,
301        examples: Vec<String>,
302        session_id: &str,
303    ) {
304        if let Some(existing) = self
305            .patterns
306            .iter_mut()
307            .find(|p| p.pattern_type == pattern_type && p.description == description)
308        {
309            for ex in &examples {
310                if !existing.examples.contains(ex) {
311                    existing.examples.push(ex.clone());
312                }
313            }
314            return;
315        }
316
317        self.patterns.push(ProjectPattern {
318            pattern_type: pattern_type.to_string(),
319            description: description.to_string(),
320            examples,
321            source_session: session_id.to_string(),
322            created_at: Utc::now(),
323        });
324
325        if self.patterns.len() > MAX_PATTERNS {
326            self.patterns.truncate(MAX_PATTERNS);
327        }
328        self.updated_at = Utc::now();
329    }
330
331    pub fn consolidate(&mut self, summary: &str, session_ids: Vec<String>) {
332        self.history.push(ConsolidatedInsight {
333            summary: summary.to_string(),
334            from_sessions: session_ids,
335            timestamp: Utc::now(),
336        });
337
338        if self.history.len() > MAX_HISTORY {
339            self.history.drain(0..self.history.len() - MAX_HISTORY);
340        }
341        self.updated_at = Utc::now();
342    }
343
344    pub fn remove_fact(&mut self, category: &str, key: &str) -> bool {
345        let before = self.facts.len();
346        self.facts
347            .retain(|f| !(f.category == category && f.key == key));
348        let removed = self.facts.len() < before;
349        if removed {
350            self.updated_at = Utc::now();
351        }
352        removed
353    }
354
355    pub fn format_summary(&self) -> String {
356        let mut out = String::new();
357        let current_facts: Vec<&KnowledgeFact> =
358            self.facts.iter().filter(|f| f.is_current()).collect();
359
360        if !current_facts.is_empty() {
361            out.push_str("PROJECT KNOWLEDGE:\n");
362            let mut categories: Vec<&str> =
363                current_facts.iter().map(|f| f.category.as_str()).collect();
364            categories.sort();
365            categories.dedup();
366
367            for cat in categories {
368                out.push_str(&format!("  [{cat}]\n"));
369                for f in current_facts.iter().filter(|f| f.category == cat) {
370                    out.push_str(&format!(
371                        "    {}: {} (confidence: {:.0}%)\n",
372                        f.key,
373                        f.value,
374                        f.confidence * 100.0
375                    ));
376                }
377            }
378        }
379
380        if !self.patterns.is_empty() {
381            out.push_str("PROJECT PATTERNS:\n");
382            for p in &self.patterns {
383                out.push_str(&format!("  [{}] {}\n", p.pattern_type, p.description));
384            }
385        }
386
387        out
388    }
389
390    pub fn format_aaak(&self) -> String {
391        let current_facts: Vec<&KnowledgeFact> =
392            self.facts.iter().filter(|f| f.is_current()).collect();
393
394        if current_facts.is_empty() && self.patterns.is_empty() {
395            return String::new();
396        }
397
398        let mut out = String::new();
399        let mut categories: Vec<&str> = current_facts.iter().map(|f| f.category.as_str()).collect();
400        categories.sort();
401        categories.dedup();
402
403        for cat in categories {
404            let facts_in_cat: Vec<&&KnowledgeFact> =
405                current_facts.iter().filter(|f| f.category == cat).collect();
406            let items: Vec<String> = facts_in_cat
407                .iter()
408                .map(|f| {
409                    let stars = confidence_stars(f.confidence);
410                    format!("{}={}{}", f.key, f.value, stars)
411                })
412                .collect();
413            out.push_str(&format!("{}:{}\n", cat.to_uppercase(), items.join("|")));
414        }
415
416        if !self.patterns.is_empty() {
417            let pat_items: Vec<String> = self
418                .patterns
419                .iter()
420                .map(|p| format!("{}.{}", p.pattern_type, p.description))
421                .collect();
422            out.push_str(&format!("PAT:{}\n", pat_items.join("|")));
423        }
424
425        out
426    }
427
428    pub fn format_wakeup(&self) -> String {
429        let current_facts: Vec<&KnowledgeFact> = self
430            .facts
431            .iter()
432            .filter(|f| f.is_current() && f.confidence >= 0.7)
433            .collect();
434
435        if current_facts.is_empty() {
436            return String::new();
437        }
438
439        let mut top_facts: Vec<&KnowledgeFact> = current_facts;
440        top_facts.sort_by(|a, b| {
441            b.confidence
442                .partial_cmp(&a.confidence)
443                .unwrap_or(std::cmp::Ordering::Equal)
444                .then_with(|| b.confirmation_count.cmp(&a.confirmation_count))
445        });
446        top_facts.truncate(10);
447
448        let items: Vec<String> = top_facts
449            .iter()
450            .map(|f| format!("{}/{}={}", f.category, f.key, f.value))
451            .collect();
452
453        format!("FACTS:{}", items.join("|"))
454    }
455
456    pub fn save(&self) -> Result<(), String> {
457        let dir = knowledge_dir(&self.project_hash)?;
458        std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
459
460        let path = dir.join("knowledge.json");
461        let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
462        std::fs::write(&path, json).map_err(|e| e.to_string())
463    }
464
465    pub fn load(project_root: &str) -> Option<Self> {
466        let hash = hash_project_root(project_root);
467        let dir = knowledge_dir(&hash).ok()?;
468        let path = dir.join("knowledge.json");
469
470        let content = std::fs::read_to_string(&path).ok()?;
471        serde_json::from_str(&content).ok()
472    }
473
474    pub fn load_or_create(project_root: &str) -> Self {
475        Self::load(project_root).unwrap_or_else(|| Self::new(project_root))
476    }
477}
478
479impl KnowledgeFact {
480    pub fn is_current(&self) -> bool {
481        self.valid_until.is_none()
482    }
483
484    pub fn was_valid_at(&self, at: DateTime<Utc>) -> bool {
485        let after_start = self.valid_from.is_none_or(|from| at >= from);
486        let before_end = self.valid_until.is_none_or(|until| at <= until);
487        after_start && before_end
488    }
489}
490
491fn confidence_stars(confidence: f32) -> &'static str {
492    if confidence >= 0.95 {
493        "★★★★★"
494    } else if confidence >= 0.85 {
495        "★★★★"
496    } else if confidence >= 0.7 {
497        "★★★"
498    } else if confidence >= 0.5 {
499        "★★"
500    } else {
501        "★"
502    }
503}
504
505fn string_similarity(a: &str, b: &str) -> f32 {
506    let a_lower = a.to_lowercase();
507    let b_lower = b.to_lowercase();
508    let a_words: std::collections::HashSet<&str> = a_lower.split_whitespace().collect();
509    let b_words: std::collections::HashSet<&str> = b_lower.split_whitespace().collect();
510
511    if a_words.is_empty() && b_words.is_empty() {
512        return 1.0;
513    }
514
515    let intersection = a_words.intersection(&b_words).count();
516    let union = a_words.union(&b_words).count();
517
518    if union == 0 {
519        return 0.0;
520    }
521
522    intersection as f32 / union as f32
523}
524
525fn knowledge_dir(project_hash: &str) -> Result<PathBuf, String> {
526    let home = dirs::home_dir().ok_or("Cannot determine home directory")?;
527    Ok(home
528        .join(".better-ctx")
529        .join("knowledge")
530        .join(project_hash))
531}
532
533fn hash_project_root(root: &str) -> String {
534    use std::collections::hash_map::DefaultHasher;
535    use std::hash::{Hash, Hasher};
536
537    let mut hasher = DefaultHasher::new();
538    root.hash(&mut hasher);
539    format!("{:016x}", hasher.finish())
540}
541
542#[cfg(test)]
543mod tests {
544    use super::*;
545
546    #[test]
547    fn remember_and_recall() {
548        let mut k = ProjectKnowledge::new("/tmp/test-project");
549        k.remember("architecture", "auth", "JWT RS256", "session-1", 0.9);
550        k.remember("api", "rate-limit", "100/min", "session-1", 0.8);
551
552        let results = k.recall("auth");
553        assert_eq!(results.len(), 1);
554        assert_eq!(results[0].value, "JWT RS256");
555
556        let results = k.recall("api rate");
557        assert_eq!(results.len(), 1);
558        assert_eq!(results[0].key, "rate-limit");
559    }
560
561    #[test]
562    fn upsert_existing_fact() {
563        let mut k = ProjectKnowledge::new("/tmp/test");
564        k.remember("arch", "db", "PostgreSQL", "s1", 0.7);
565        k.remember("arch", "db", "PostgreSQL 16 with pgvector", "s2", 0.95);
566
567        let current: Vec<_> = k.facts.iter().filter(|f| f.is_current()).collect();
568        assert_eq!(current.len(), 1);
569        assert_eq!(current[0].value, "PostgreSQL 16 with pgvector");
570    }
571
572    #[test]
573    fn contradiction_detection() {
574        let mut k = ProjectKnowledge::new("/tmp/test");
575        k.remember("arch", "db", "PostgreSQL", "s1", 0.95);
576        k.facts[0].confirmation_count = 3;
577
578        let contradiction = k.check_contradiction("arch", "db", "MySQL");
579        assert!(contradiction.is_some());
580        let c = contradiction.unwrap();
581        assert_eq!(c.severity, ContradictionSeverity::High);
582    }
583
584    #[test]
585    fn temporal_validity() {
586        let mut k = ProjectKnowledge::new("/tmp/test");
587        k.remember("arch", "db", "PostgreSQL", "s1", 0.95);
588        k.facts[0].confirmation_count = 3;
589
590        k.remember("arch", "db", "MySQL", "s2", 0.9);
591
592        let current: Vec<_> = k.facts.iter().filter(|f| f.is_current()).collect();
593        assert_eq!(current.len(), 1);
594        assert_eq!(current[0].value, "MySQL");
595
596        let all_db: Vec<_> = k.facts.iter().filter(|f| f.key == "db").collect();
597        assert_eq!(all_db.len(), 2);
598    }
599
600    #[test]
601    fn confirmation_count() {
602        let mut k = ProjectKnowledge::new("/tmp/test");
603        k.remember("arch", "db", "PostgreSQL", "s1", 0.9);
604        assert_eq!(k.facts[0].confirmation_count, 1);
605
606        k.remember("arch", "db", "PostgreSQL", "s2", 0.9);
607        assert_eq!(k.facts[0].confirmation_count, 2);
608    }
609
610    #[test]
611    fn remove_fact() {
612        let mut k = ProjectKnowledge::new("/tmp/test");
613        k.remember("arch", "db", "PostgreSQL", "s1", 0.9);
614        assert!(k.remove_fact("arch", "db"));
615        assert!(k.facts.is_empty());
616        assert!(!k.remove_fact("arch", "db"));
617    }
618
619    #[test]
620    fn list_rooms() {
621        let mut k = ProjectKnowledge::new("/tmp/test");
622        k.remember("architecture", "auth", "JWT", "s1", 0.9);
623        k.remember("architecture", "db", "PG", "s1", 0.9);
624        k.remember("deploy", "host", "AWS", "s1", 0.8);
625
626        let rooms = k.list_rooms();
627        assert_eq!(rooms.len(), 2);
628    }
629
630    #[test]
631    fn aaak_format() {
632        let mut k = ProjectKnowledge::new("/tmp/test");
633        k.remember("architecture", "auth", "JWT RS256", "s1", 0.95);
634        k.remember("architecture", "db", "PostgreSQL", "s1", 0.7);
635
636        let aaak = k.format_aaak();
637        assert!(aaak.contains("ARCHITECTURE:"));
638        assert!(aaak.contains("auth=JWT RS256"));
639    }
640
641    #[test]
642    fn consolidate_history() {
643        let mut k = ProjectKnowledge::new("/tmp/test");
644        k.consolidate(
645            "Migrated from REST to GraphQL",
646            vec!["s1".into(), "s2".into()],
647        );
648        assert_eq!(k.history.len(), 1);
649        assert_eq!(k.history[0].from_sessions.len(), 2);
650    }
651
652    #[test]
653    fn format_summary_output() {
654        let mut k = ProjectKnowledge::new("/tmp/test");
655        k.remember("architecture", "auth", "JWT RS256", "s1", 0.9);
656        k.add_pattern(
657            "naming",
658            "snake_case for functions",
659            vec!["get_user()".into()],
660            "s1",
661        );
662        let summary = k.format_summary();
663        assert!(summary.contains("PROJECT KNOWLEDGE:"));
664        assert!(summary.contains("auth: JWT RS256"));
665        assert!(summary.contains("PROJECT PATTERNS:"));
666    }
667
668    #[test]
669    fn temporal_recall_at_time() {
670        let mut k = ProjectKnowledge::new("/tmp/test");
671        k.remember("arch", "db", "PostgreSQL", "s1", 0.95);
672        k.facts[0].confirmation_count = 3;
673
674        let before_change = Utc::now();
675        std::thread::sleep(std::time::Duration::from_millis(10));
676
677        k.remember("arch", "db", "MySQL", "s2", 0.9);
678
679        let results = k.recall_at_time("db", before_change);
680        assert_eq!(results.len(), 1);
681        assert_eq!(results[0].value, "PostgreSQL");
682
683        let results_now = k.recall_at_time("db", Utc::now());
684        assert_eq!(results_now.len(), 1);
685        assert_eq!(results_now[0].value, "MySQL");
686    }
687
688    #[test]
689    fn timeline_shows_history() {
690        let mut k = ProjectKnowledge::new("/tmp/test");
691        k.remember("arch", "db", "PostgreSQL", "s1", 0.95);
692        k.facts[0].confirmation_count = 3;
693        k.remember("arch", "db", "MySQL", "s2", 0.9);
694
695        let timeline = k.timeline("arch");
696        assert_eq!(timeline.len(), 2);
697        assert!(!timeline[0].is_current());
698        assert!(timeline[1].is_current());
699    }
700
701    #[test]
702    fn wakeup_format() {
703        let mut k = ProjectKnowledge::new("/tmp/test");
704        k.remember("arch", "auth", "JWT", "s1", 0.95);
705        k.remember("arch", "db", "PG", "s1", 0.8);
706
707        let wakeup = k.format_wakeup();
708        assert!(wakeup.contains("FACTS:"));
709        assert!(wakeup.contains("arch/auth=JWT"));
710        assert!(wakeup.contains("arch/db=PG"));
711    }
712
713    #[test]
714    fn low_confidence_contradiction() {
715        let mut k = ProjectKnowledge::new("/tmp/test");
716        k.remember("arch", "db", "PostgreSQL", "s1", 0.4);
717
718        let c = k.check_contradiction("arch", "db", "MySQL");
719        assert!(c.is_some());
720        assert_eq!(c.unwrap().severity, ContradictionSeverity::Low);
721    }
722
723    #[test]
724    fn no_contradiction_for_same_value() {
725        let mut k = ProjectKnowledge::new("/tmp/test");
726        k.remember("arch", "db", "PostgreSQL", "s1", 0.95);
727
728        let c = k.check_contradiction("arch", "db", "PostgreSQL");
729        assert!(c.is_none());
730    }
731
732    #[test]
733    fn no_contradiction_for_similar_values() {
734        let mut k = ProjectKnowledge::new("/tmp/test");
735        k.remember(
736            "arch",
737            "db",
738            "PostgreSQL 16 production database server",
739            "s1",
740            0.95,
741        );
742
743        let c = k.check_contradiction(
744            "arch",
745            "db",
746            "PostgreSQL 16 production database server config",
747        );
748        assert!(c.is_none());
749    }
750}