Skip to main content

clm_rust_core/layer4/
navigation.rs

1//! Card Graph Navigation Modalities — Sprint 364
2//!
3//! Provides the three navigation modalities over the MCard knowledge graph:
4//! 1. Covariant: forward traversal along next fireable downstream PCards.
5//! 2. Contravariant: backward traversal along upstream VCard execution provenance.
6//! 3. Invariant: equivalence grouping across isomorphic content-equivalent MCards.
7
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12pub enum NavigationDirection {
13    Covariant,
14    Contravariant,
15    Invariant,
16}
17
18#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
19pub struct CardNode {
20    pub hash: String,
21    pub handle: Option<String>,
22    pub card_type: String,
23    pub content_hash: String,
24    pub upstream_vcards: Vec<String>,
25    pub downstream_pcards: Vec<String>,
26}
27
28pub struct CardGraph {
29    pub nodes: HashMap<String, CardNode>,
30}
31
32impl Default for CardGraph {
33    fn default() -> Self {
34        Self::new()
35    }
36}
37
38impl CardGraph {
39    pub fn new() -> Self {
40        Self {
41            nodes: HashMap::new(),
42        }
43    }
44
45    pub fn insert_node(&mut self, node: CardNode) {
46        self.nodes.insert(node.hash.clone(), node);
47    }
48
49    pub fn navigate(&self, start_hash: &str, direction: NavigationDirection) -> Vec<String> {
50        let node = match self.nodes.get(start_hash) {
51            Some(n) => n,
52            None => return Vec::new(),
53        };
54
55        match direction {
56            NavigationDirection::Covariant => {
57                let mut results = node.downstream_pcards.clone();
58                results.sort();
59                results
60            }
61            NavigationDirection::Contravariant => {
62                let mut results = node.upstream_vcards.clone();
63                results.sort();
64                results
65            }
66            NavigationDirection::Invariant => {
67                let mut results: Vec<String> = self
68                    .nodes
69                    .values()
70                    .filter(|n| n.content_hash == node.content_hash)
71                    .map(|n| n.hash.clone())
72                    .collect();
73                results.sort();
74                results
75            }
76        }
77    }
78}