Skip to main content

lean_ctx/core/
knowledge_bridge.rs

1//! Cross-Agent Knowledge Bridge — controlled sharing of high-confidence facts between agents.
2
3use chrono::{DateTime, Utc};
4use serde::{Deserialize, Serialize};
5use std::path::PathBuf;
6
7use crate::core::knowledge::{KnowledgeArchetype, KnowledgeFact};
8use crate::core::memory_boundary::FactPrivacy;
9
10const PUBLISHABLE_ARCHETYPES: &[KnowledgeArchetype] = &[
11    KnowledgeArchetype::Architecture,
12    KnowledgeArchetype::Convention,
13    KnowledgeArchetype::Decision,
14    KnowledgeArchetype::Dependency,
15    KnowledgeArchetype::Gotcha,
16];
17
18const MIN_PUBLISH_CONFIDENCE: f32 = 0.8;
19
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct BridgeEntry {
22    #[serde(default)]
23    pub origin: crate::core::knowledge::FactOrigin,
24    pub fact_key: String,
25    pub fact_category: String,
26    pub fact_value: String,
27    pub source_agent: String,
28    pub published_at: DateTime<Utc>,
29    pub archetype: KnowledgeArchetype,
30    pub confidence: f32,
31    pub provenance: String,
32}
33
34#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct KnowledgeBridge {
36    pub project_hash: String,
37    pub shared_facts: Vec<BridgeEntry>,
38    pub updated_at: DateTime<Utc>,
39}
40
41impl KnowledgeBridge {
42    pub fn new(project_hash: &str) -> Self {
43        Self {
44            project_hash: project_hash.to_string(),
45            shared_facts: Vec::new(),
46            updated_at: Utc::now(),
47        }
48    }
49
50    pub fn path(project_hash: &str) -> Result<PathBuf, String> {
51        Ok(crate::core::data_dir::lean_ctx_data_dir()?
52            .join("knowledge")
53            .join(project_hash)
54            .join("bridge.json"))
55    }
56
57    pub fn load(project_hash: &str) -> Option<Self> {
58        let path = Self::path(project_hash).ok()?;
59        let content = std::fs::read_to_string(&path).ok()?;
60        serde_json::from_str::<Self>(&content).ok()
61    }
62
63    pub fn load_or_create(project_hash: &str) -> Self {
64        Self::load(project_hash).unwrap_or_else(|| Self::new(project_hash))
65    }
66
67    pub fn save(&mut self) -> Result<(), String> {
68        self.updated_at = Utc::now();
69        let path = Self::path(&self.project_hash)?;
70        if let Some(parent) = path.parent() {
71            std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
72        }
73        let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
74        crate::config_io::write_atomic(&path, &json)
75    }
76
77    /// Publish eligible facts from an agent's knowledge store.
78    /// Only publishes facts with sufficient confidence, a publishable archetype,
79    /// and that haven't already been published by this agent.
80    pub fn publish(&mut self, agent_id: &str, facts: &[KnowledgeFact]) -> u32 {
81        let mut count = 0u32;
82        for fact in facts {
83            if !fact.is_current() {
84                continue;
85            }
86            if fact.confidence < MIN_PUBLISH_CONFIDENCE {
87                continue;
88            }
89            if !PUBLISHABLE_ARCHETYPES.contains(&fact.archetype) {
90                continue;
91            }
92            let already_published = self.shared_facts.iter().any(|e| {
93                e.fact_key == fact.key
94                    && e.fact_category == fact.category
95                    && e.source_agent == agent_id
96            });
97            if already_published {
98                continue;
99            }
100            self.shared_facts.push(BridgeEntry {
101                origin: fact.origin.clone(),
102                fact_key: fact.key.clone(),
103                fact_category: fact.category.clone(),
104                fact_value: fact.value.clone(),
105                source_agent: agent_id.to_string(),
106                published_at: Utc::now(),
107                archetype: fact.archetype.clone(),
108                confidence: fact.confidence,
109                provenance: fact.source_session.clone(),
110            });
111            count += 1;
112        }
113        count
114    }
115
116    /// Pull facts from the bridge that were published by other agents.
117    pub fn pull(&self, requesting_agent: &str) -> Vec<BridgeEntry> {
118        self.shared_facts
119            .iter()
120            .filter(|e| e.source_agent != requesting_agent)
121            .cloned()
122            .collect()
123    }
124
125    /// Convert a [`BridgeEntry`] into a [`KnowledgeFact`] for import.
126    /// Applies a 10% trust penalty to imported confidence.
127    pub fn entry_to_fact(entry: &BridgeEntry) -> KnowledgeFact {
128        let now = Utc::now();
129        KnowledgeFact {
130            origin: crate::core::knowledge::source_view::imported_origin(&entry.origin),
131            category: entry.fact_category.clone(),
132            key: entry.fact_key.clone(),
133            value: entry.fact_value.clone(),
134            source_session: entry.provenance.clone(),
135            confidence: entry.confidence * 0.9,
136            created_at: now,
137            last_confirmed: now,
138            retrieval_count: 0,
139            last_retrieved: None,
140            valid_from: Some(now),
141            valid_until: None,
142            supersedes: None,
143            confirmation_count: 1,
144            feedback_up: 0,
145            feedback_down: 0,
146            last_feedback: None,
147            privacy: FactPrivacy::default(),
148            sensitivity: crate::core::sensitivity::classify_content(&entry.fact_value),
149            imported_from: Some(format!("bridge:{}", entry.source_agent)),
150            archetype: entry.archetype.clone(),
151            fidelity: None,
152            revision_count: 0,
153        }
154    }
155
156    /// Remove entries older than `max_age_days` or below `min_confidence`.
157    pub fn cleanup(&mut self, max_age_days: i64, min_confidence: f32) -> usize {
158        let cutoff = Utc::now() - chrono::Duration::days(max_age_days);
159        let before = self.shared_facts.len();
160        self.shared_facts
161            .retain(|e| e.published_at >= cutoff && e.confidence >= min_confidence);
162        before - self.shared_facts.len()
163    }
164
165    pub fn entries_for_agent(&self, agent_id: &str) -> Vec<&BridgeEntry> {
166        self.shared_facts
167            .iter()
168            .filter(|e| e.source_agent == agent_id)
169            .collect()
170    }
171
172    pub fn summary(&self) -> String {
173        if self.shared_facts.is_empty() {
174            return format!(
175                "Knowledge Bridge [{}]: empty",
176                short_hash(&self.project_hash)
177            );
178        }
179
180        let mut agents: std::collections::HashMap<&str, u32> = std::collections::HashMap::new();
181        for entry in &self.shared_facts {
182            *agents.entry(&entry.source_agent).or_default() += 1;
183        }
184
185        let mut out = format!(
186            "Knowledge Bridge [{}]: {} shared facts from {} agent(s)\n",
187            short_hash(&self.project_hash),
188            self.shared_facts.len(),
189            agents.len(),
190        );
191        let mut sorted_agents: Vec<_> = agents.into_iter().collect();
192        sorted_agents.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(b.0)));
193        for (agent, count) in &sorted_agents {
194            out.push_str(&format!("  {agent}: {count} fact(s)\n"));
195        }
196        out.push_str(&format!(
197            "Last updated: {}",
198            self.updated_at.format("%Y-%m-%d %H:%M UTC")
199        ));
200        out
201    }
202}
203
204fn short_hash(hash: &str) -> &str {
205    if hash.len() > 8 { &hash[..8] } else { hash }
206}
207
208#[cfg(test)]
209pub mod tests {
210    use super::*;
211    use crate::core::knowledge::KnowledgeFact;
212    use crate::core::memory_boundary::FactPrivacy;
213
214    fn make_fact(
215        cat: &str,
216        key: &str,
217        val: &str,
218        confidence: f32,
219        archetype: KnowledgeArchetype,
220    ) -> KnowledgeFact {
221        KnowledgeFact {
222            origin: crate::core::knowledge::FactOrigin::Local,
223            category: cat.into(),
224            key: key.into(),
225            value: val.into(),
226            source_session: "test-session".into(),
227            confidence,
228            created_at: Utc::now(),
229            last_confirmed: Utc::now(),
230            retrieval_count: 0,
231            last_retrieved: None,
232            valid_from: None,
233            valid_until: None,
234            supersedes: None,
235            confirmation_count: 1,
236            feedback_up: 0,
237            feedback_down: 0,
238            last_feedback: None,
239            privacy: FactPrivacy::default(),
240            sensitivity: crate::core::sensitivity::SensitivityLevel::default(),
241            imported_from: None,
242            archetype,
243            fidelity: None,
244            revision_count: 0,
245        }
246    }
247
248    #[test]
249    fn publish_only_eligible_facts() {
250        let mut bridge = KnowledgeBridge::new("test-hash");
251        let facts = vec![
252            make_fact(
253                "arch",
254                "db",
255                "PostgreSQL",
256                0.9,
257                KnowledgeArchetype::Architecture,
258            ),
259            make_fact("random", "x", "low-conf", 0.3, KnowledgeArchetype::Fact),
260            make_fact(
261                "gotcha",
262                "trap",
263                "watch out",
264                0.85,
265                KnowledgeArchetype::Gotcha,
266            ),
267            make_fact(
268                "pref",
269                "editor",
270                "vim",
271                0.95,
272                KnowledgeArchetype::Preference,
273            ),
274        ];
275        let count = bridge.publish("agent-1", &facts);
276        assert_eq!(count, 2);
277        assert_eq!(bridge.shared_facts.len(), 2);
278    }
279
280    #[test]
281    fn pull_excludes_own_facts() {
282        let mut bridge = KnowledgeBridge::new("test-hash");
283        let facts = vec![make_fact(
284            "arch",
285            "db",
286            "PostgreSQL",
287            0.9,
288            KnowledgeArchetype::Architecture,
289        )];
290        bridge.publish("agent-1", &facts);
291
292        let pulled = bridge.pull("agent-1");
293        assert!(pulled.is_empty(), "Should not pull own facts");
294
295        let pulled = bridge.pull("agent-2");
296        assert_eq!(pulled.len(), 1);
297    }
298
299    #[test]
300    fn entry_to_fact_preserves_provenance() {
301        let entry = BridgeEntry {
302            origin: crate::core::knowledge::FactOrigin::Local,
303            fact_key: "db".into(),
304            fact_category: "arch".into(),
305            fact_value: "PostgreSQL".into(),
306            source_agent: "agent-1".into(),
307            published_at: Utc::now(),
308            archetype: KnowledgeArchetype::Architecture,
309            confidence: 0.9,
310            provenance: "session-abc".into(),
311        };
312        let fact = KnowledgeBridge::entry_to_fact(&entry);
313        assert_eq!(fact.imported_from, Some("bridge:agent-1".into()));
314        assert!(fact.confidence < 0.9);
315        assert_eq!(fact.archetype, KnowledgeArchetype::Architecture);
316    }
317
318    #[test]
319    fn no_duplicate_publish() {
320        let mut bridge = KnowledgeBridge::new("test-hash");
321        let facts = vec![make_fact(
322            "arch",
323            "db",
324            "PostgreSQL",
325            0.9,
326            KnowledgeArchetype::Architecture,
327        )];
328        bridge.publish("agent-1", &facts);
329        let second = bridge.publish("agent-1", &facts);
330        assert_eq!(second, 0, "Should not re-publish same fact");
331        assert_eq!(bridge.shared_facts.len(), 1);
332    }
333
334    #[test]
335    fn cleanup_removes_old_entries() {
336        let mut bridge = KnowledgeBridge::new("test-hash");
337        bridge.shared_facts.push(BridgeEntry {
338            origin: crate::core::knowledge::FactOrigin::Local,
339            fact_key: "old".into(),
340            fact_category: "arch".into(),
341            fact_value: "ancient".into(),
342            source_agent: "agent-1".into(),
343            published_at: Utc::now() - chrono::Duration::days(60),
344            archetype: KnowledgeArchetype::Architecture,
345            confidence: 0.9,
346            provenance: "old-session".into(),
347        });
348        bridge.shared_facts.push(BridgeEntry {
349            origin: crate::core::knowledge::FactOrigin::Local,
350            fact_key: "fresh".into(),
351            fact_category: "arch".into(),
352            fact_value: "new".into(),
353            source_agent: "agent-1".into(),
354            published_at: Utc::now(),
355            archetype: KnowledgeArchetype::Architecture,
356            confidence: 0.9,
357            provenance: "new-session".into(),
358        });
359        let removed = bridge.cleanup(30, 0.5);
360        assert_eq!(removed, 1);
361        assert_eq!(bridge.shared_facts.len(), 1);
362        assert_eq!(bridge.shared_facts[0].fact_key, "fresh");
363    }
364
365    #[test]
366    fn entries_for_agent_filters_correctly() {
367        let mut bridge = KnowledgeBridge::new("test-hash");
368        let facts_a = vec![make_fact(
369            "arch",
370            "db",
371            "PostgreSQL",
372            0.9,
373            KnowledgeArchetype::Architecture,
374        )];
375        let facts_b = vec![make_fact(
376            "gotcha",
377            "trap",
378            "watch out",
379            0.85,
380            KnowledgeArchetype::Gotcha,
381        )];
382        bridge.publish("agent-a", &facts_a);
383        bridge.publish("agent-b", &facts_b);
384
385        assert_eq!(bridge.entries_for_agent("agent-a").len(), 1);
386        assert_eq!(bridge.entries_for_agent("agent-b").len(), 1);
387        assert_eq!(bridge.entries_for_agent("agent-c").len(), 0);
388    }
389
390    #[test]
391    fn summary_format() {
392        let mut bridge = KnowledgeBridge::new("test-hash");
393        assert!(bridge.summary().contains("empty"));
394
395        let facts = vec![make_fact(
396            "arch",
397            "db",
398            "PostgreSQL",
399            0.9,
400            KnowledgeArchetype::Architecture,
401        )];
402        bridge.publish("agent-1", &facts);
403        let summary = bridge.summary();
404        assert!(summary.contains("1 shared facts"));
405        assert!(summary.contains("agent-1"));
406    }
407
408    #[test]
409    fn cleanup_removes_low_confidence() {
410        let mut bridge = KnowledgeBridge::new("test-hash");
411        bridge.shared_facts.push(BridgeEntry {
412            origin: crate::core::knowledge::FactOrigin::Local,
413            fact_key: "weak".into(),
414            fact_category: "arch".into(),
415            fact_value: "uncertain".into(),
416            source_agent: "agent-1".into(),
417            published_at: Utc::now(),
418            archetype: KnowledgeArchetype::Architecture,
419            confidence: 0.3,
420            provenance: "session".into(),
421        });
422        bridge.shared_facts.push(BridgeEntry {
423            origin: crate::core::knowledge::FactOrigin::Local,
424            fact_key: "strong".into(),
425            fact_category: "arch".into(),
426            fact_value: "certain".into(),
427            source_agent: "agent-1".into(),
428            published_at: Utc::now(),
429            archetype: KnowledgeArchetype::Architecture,
430            confidence: 0.9,
431            provenance: "session".into(),
432        });
433        let removed = bridge.cleanup(365, 0.5);
434        assert_eq!(removed, 1);
435        assert_eq!(bridge.shared_facts[0].fact_key, "strong");
436    }
437
438    #[test]
439    fn trust_penalty_reduces_confidence() {
440        let entry = BridgeEntry {
441            origin: crate::core::knowledge::FactOrigin::Local,
442            fact_key: "k".into(),
443            fact_category: "c".into(),
444            fact_value: "v".into(),
445            source_agent: "src".into(),
446            published_at: Utc::now(),
447            archetype: KnowledgeArchetype::Decision,
448            confidence: 1.0,
449            provenance: "s".into(),
450        };
451        let fact = KnowledgeBridge::entry_to_fact(&entry);
452        assert!((fact.confidence - 0.9).abs() < f32::EPSILON);
453    }
454
455    #[test]
456    fn archived_facts_not_published() {
457        let mut bridge = KnowledgeBridge::new("test-hash");
458        let mut fact = make_fact(
459            "arch",
460            "old-db",
461            "MySQL",
462            0.95,
463            KnowledgeArchetype::Architecture,
464        );
465        fact.valid_until = Some(Utc::now() - chrono::Duration::days(1));
466        let count = bridge.publish("agent-1", &[fact]);
467        assert_eq!(count, 0);
468    }
469}