Skip to main content

lean_ctx_ext/core/
knowledge_bridge.rs

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