Skip to main content

qualia_core_db/research/
hypothesis.rs

1//! Hypothesis graph — multi-agent collaborative hypothesis revision.
2
3use std::collections::BTreeMap;
4
5/// A node in the hypothesis graph.
6#[derive(Debug, Clone)]
7pub struct HypothesisNode {
8    pub id: String,
9    pub statement: String,
10    pub agent_id: String,
11    pub evaluations: Vec<Evaluation>,
12    pub dark_links: Vec<String>,
13    pub gaps: Vec<String>,
14    pub status: NodeStatus,
15}
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum NodeStatus {
19    Open,
20    Bridged,
21    Closed,
22    Reframed,
23    Merged,
24}
25
26/// An evaluation contributed by an agent.
27#[derive(Debug, Clone)]
28pub struct Evaluation {
29    pub agent_id: String,
30    pub assessment: String,
31    pub score: f64,
32    pub timestamp: String,
33}
34
35/// A revision of a hypothesis node.
36#[derive(Debug, Clone)]
37pub struct HypothesisRevision {
38    pub node_id: String,
39    pub revision_id: String,
40    pub old_statement: String,
41    pub new_statement: String,
42    pub agent_id: String,
43    pub timestamp: String,
44}
45
46/// The hypothesis graph — multi-agent collaborative structure.
47#[derive(Debug, Clone, Default)]
48pub struct HypothesisGraph {
49    pub nodes: BTreeMap<String, HypothesisNode>,
50    pub revisions: Vec<HypothesisRevision>,
51    pub subscribers: BTreeMap<String, Vec<String>>, // node_id -> agent_ids
52}
53
54impl HypothesisGraph {
55    /// Creates an empty hypothesis graph (nodes, revisions, subscribers).
56    pub fn new() -> Self {
57        Self::default()
58    }
59
60    /// Inserts `node` into the graph keyed by its id.
61    pub fn create(&mut self, node: HypothesisNode) {
62        self.nodes.insert(node.id.clone(), node);
63    }
64
65    /// Attaches `evaluation` to node `node_id`; `false` when unknown.
66    pub fn add_to_graph(&mut self, node_id: &str, evaluation: Evaluation) -> bool {
67        if let Some(node) = self.nodes.get_mut(node_id) {
68            node.evaluations.push(evaluation);
69            true
70        } else {
71            false
72        }
73    }
74
75    /// Records a contributed `evaluation` on node `node_id`; `false` when unknown.
76    pub fn contribute_evaluation(&mut self, node_id: &str, evaluation: Evaluation) -> bool {
77        self.add_to_graph(node_id, evaluation)
78    }
79
80    /// Links node `node_id` to a dark-link id; `false` when unknown.
81    pub fn bridge_dark_link(&mut self, node_id: &str, dark_link_id: &str) -> bool {
82        if let Some(node) = self.nodes.get_mut(node_id) {
83            node.dark_links.push(dark_link_id.to_string());
84            node.status = NodeStatus::Bridged;
85            true
86        } else {
87            false
88        }
89    }
90
91    /// Rewrites the node statement, marks it `Reframed`, and appends a `HypothesisRevision`; `false` when unknown.
92    pub fn reframe_hypothesis(
93        &mut self,
94        node_id: &str,
95        new_statement: &str,
96        agent_id: &str,
97        timestamp: &str,
98    ) -> bool {
99        if let Some(node) = self.nodes.get_mut(node_id) {
100            let revision = HypothesisRevision {
101                node_id: node_id.to_string(),
102                revision_id: format!("rev_{}", self.revisions.len()),
103                old_statement: node.statement.clone(),
104                new_statement: new_statement.to_string(),
105                agent_id: agent_id.to_string(),
106                timestamp: timestamp.to_string(),
107            };
108            node.statement = new_statement.to_string();
109            node.status = NodeStatus::Reframed;
110            self.revisions.push(revision);
111            true
112        } else {
113            false
114        }
115    }
116
117    /// Merges two nodes: `node1` takes `merged_statement`, both marked `Merged`, and a merge revision is appended; `false` when either id is unknown.
118    pub fn merge_hypotheses(
119        &mut self,
120        node1_id: &str,
121        node2_id: &str,
122        merged_statement: &str,
123        agent_id: &str,
124        timestamp: &str,
125    ) -> bool {
126        if !self.nodes.contains_key(node1_id) || !self.nodes.contains_key(node2_id) {
127            return false;
128        }
129        // Mark both as merged and create a combined statement on node1.
130        if let Some(node) = self.nodes.get_mut(node1_id) {
131            node.statement = merged_statement.to_string();
132            node.status = NodeStatus::Merged;
133        }
134        if let Some(node) = self.nodes.get_mut(node2_id) {
135            node.status = NodeStatus::Merged;
136        }
137        let revision = HypothesisRevision {
138            node_id: node1_id.to_string(),
139            revision_id: format!("merge_{}", self.revisions.len()),
140            old_statement: "pre-merge".to_string(),
141            new_statement: merged_statement.to_string(),
142            agent_id: agent_id.to_string(),
143            timestamp: timestamp.to_string(),
144        };
145        self.revisions.push(revision);
146        true
147    }
148
149    /// Appends `gap` to the node's gap list; `false` when unknown.
150    pub fn flag_gap(&mut self, node_id: &str, gap: &str) -> bool {
151        if let Some(node) = self.nodes.get_mut(node_id) {
152            node.gaps.push(gap.to_string());
153            true
154        } else {
155            false
156        }
157    }
158
159    /// Removes `gap`; marks node `Closed` when no gaps remain; `false` when node or gap unknown.
160    pub fn close_gap(&mut self, node_id: &str, gap: &str) -> bool {
161        if let Some(node) = self.nodes.get_mut(node_id) {
162            if let Some(pos) = node.gaps.iter().position(|g| g == gap) {
163                node.gaps.remove(pos);
164                if node.gaps.is_empty() {
165                    node.status = NodeStatus::Closed;
166                }
167                true
168            } else {
169                false
170            }
171        } else {
172            false
173        }
174    }
175
176    /// Reframes the node and returns the new revision id; `None` when the node is unknown.
177    pub fn create_revision(
178        &mut self,
179        node_id: &str,
180        new_statement: &str,
181        agent_id: &str,
182        timestamp: &str,
183    ) -> Option<String> {
184        let rev_id = format!("rev_{}", self.revisions.len());
185        if self.reframe_hypothesis(node_id, new_statement, agent_id, timestamp) {
186            Some(rev_id)
187        } else {
188            None
189        }
190    }
191
192    /// Looks up two revisions by id, returning both for comparison; `None` when either is missing.
193    pub fn diff_revisions(
194        &self,
195        rev1_id: &str,
196        rev2_id: &str,
197    ) -> Option<(&HypothesisRevision, &HypothesisRevision)> {
198        let r1 = self.revisions.iter().find(|r| r.revision_id == rev1_id)?;
199        let r2 = self.revisions.iter().find(|r| r.revision_id == rev2_id)?;
200        Some((r1, r2))
201    }
202
203    /// Subscribes `agent_id` to updates on node `node_id`.
204    pub fn subscribe_updates(&mut self, node_id: &str, agent_id: &str) {
205        self.subscribers
206            .entry(node_id.to_string())
207            .or_default()
208            .push(agent_id.to_string());
209    }
210
211    /// Number of nodes in the graph.
212    pub fn node_count(&self) -> usize {
213        self.nodes.len()
214    }
215
216    /// Number of recorded revisions.
217    pub fn revision_count(&self) -> usize {
218        self.revisions.len()
219    }
220}
221
222impl HypothesisNode {
223    /// Creates a hypothesis node with `statement`, authored by `agent_id`, in `Proposed` status.
224    pub fn new(id: &str, statement: &str, agent_id: &str) -> Self {
225        Self {
226            id: id.to_string(),
227            statement: statement.to_string(),
228            agent_id: agent_id.to_string(),
229            evaluations: Vec::new(),
230            dark_links: Vec::new(),
231            gaps: Vec::new(),
232            status: NodeStatus::Open,
233        }
234    }
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240
241    #[test]
242    fn graph_create() {
243        let mut graph = HypothesisGraph::new();
244        graph.create(HypothesisNode::new("h1", "X causes Y", "agent_a"));
245        assert_eq!(graph.node_count(), 1);
246    }
247
248    #[test]
249    fn graph_add_evaluation() {
250        let mut graph = HypothesisGraph::new();
251        graph.create(HypothesisNode::new("h1", "X causes Y", "agent_a"));
252        graph.add_to_graph(
253            "h1",
254            Evaluation {
255                agent_id: "agent_b".into(),
256                assessment: "Strong support".into(),
257                score: 0.9,
258                timestamp: "2024-01-01".into(),
259            },
260        );
261        assert_eq!(graph.nodes.get("h1").unwrap().evaluations.len(), 1);
262    }
263
264    #[test]
265    fn graph_bridge_dark_link() {
266        let mut graph = HypothesisGraph::new();
267        graph.create(HypothesisNode::new("h1", "X causes Y", "agent_a"));
268        graph.bridge_dark_link("h1", "dl1");
269        assert_eq!(graph.nodes.get("h1").unwrap().status, NodeStatus::Bridged);
270    }
271
272    #[test]
273    fn graph_reframe() {
274        let mut graph = HypothesisGraph::new();
275        graph.create(HypothesisNode::new("h1", "X causes Y", "agent_a"));
276        graph.reframe_hypothesis("h1", "X and Z jointly cause Y", "agent_b", "2024-02-01");
277        assert_eq!(graph.nodes.get("h1").unwrap().status, NodeStatus::Reframed);
278        assert_eq!(graph.revision_count(), 1);
279    }
280
281    #[test]
282    fn graph_merge() {
283        let mut graph = HypothesisGraph::new();
284        graph.create(HypothesisNode::new("h1", "X causes Y", "agent_a"));
285        graph.create(HypothesisNode::new("h2", "Z causes Y", "agent_b"));
286        assert!(graph.merge_hypotheses(
287            "h1",
288            "h2",
289            "X and Z jointly cause Y",
290            "agent_c",
291            "2024-03-01"
292        ));
293        assert_eq!(graph.nodes.get("h1").unwrap().status, NodeStatus::Merged);
294        assert_eq!(graph.nodes.get("h2").unwrap().status, NodeStatus::Merged);
295    }
296
297    #[test]
298    fn graph_flag_and_close_gap() {
299        let mut graph = HypothesisGraph::new();
300        graph.create(HypothesisNode::new("h1", "X causes Y", "agent_a"));
301        graph.flag_gap("h1", "Missing evidence for X");
302        assert_eq!(graph.nodes.get("h1").unwrap().gaps.len(), 1);
303        graph.close_gap("h1", "Missing evidence for X");
304        assert!(graph.nodes.get("h1").unwrap().gaps.is_empty());
305        assert_eq!(graph.nodes.get("h1").unwrap().status, NodeStatus::Closed);
306    }
307
308    #[test]
309    fn graph_subscribe() {
310        let mut graph = HypothesisGraph::new();
311        graph.create(HypothesisNode::new("h1", "X causes Y", "agent_a"));
312        graph.subscribe_updates("h1", "agent_b");
313        assert!(graph
314            .subscribers
315            .get("h1")
316            .unwrap()
317            .contains(&"agent_b".to_string()));
318    }
319
320    #[test]
321    fn graph_diff_revisions() {
322        let mut graph = HypothesisGraph::new();
323        graph.create(HypothesisNode::new("h1", "Original", "agent_a"));
324        graph.reframe_hypothesis("h1", "Revised 1", "agent_b", "t1");
325        graph.reframe_hypothesis("h1", "Revised 2", "agent_c", "t2");
326        let diff = graph.diff_revisions("rev_0", "rev_1");
327        assert!(diff.is_some());
328    }
329}