Skip to main content

zeitgeist_protocol/
consensus.rs

1//! Consensus tracking — holonomy state + CRDT version vector
2
3use serde::{Deserialize, Serialize};
4use std::collections::BTreeMap;
5
6/// Consensus state captures cycle coherence via holonomy integral
7/// and peer agreement with a CRDT version vector.
8#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
9pub struct ConsensusState {
10    /// Cycle integral (0 = coherent)
11    pub holonomy: f64,
12    /// Fraction of agreeing peers (0-1)
13    pub peer_agreement: f64,
14    /// State vector clock (agent_id -> version)
15    pub crdt_version: BTreeMap<u64, u64>,
16}
17
18impl ConsensusState {
19    pub fn new(holonomy: f64, peer_agreement: f64, crdt_version: BTreeMap<u64, u64>) -> Self {
20        Self { holonomy, peer_agreement, crdt_version }
21    }
22
23    pub fn default() -> Self {
24        Self {
25            holonomy: 0.0,
26            peer_agreement: 1.0,
27            crdt_version: BTreeMap::new(),
28        }
29    }
30
31    /// Check alignment: holonomy should approach 0
32    pub fn check_alignment(&self) -> Vec<String> {
33        let mut violations = Vec::new();
34        if !(0.0..=1.0).contains(&self.peer_agreement) {
35            violations.push("consensus.peer_agreement must be 0-1".into());
36        }
37        violations
38    }
39
40    /// Merge: min holonomy (most coherent), max peer agreement,
41    /// supmerge version vectors (pointwise max). All semilattice operations.
42    pub fn merge(&self, other: &Self) -> Self {
43        let holonomy = self.holonomy.min(other.holonomy);
44        let peer_agreement = self.peer_agreement.max(other.peer_agreement);
45
46        // CRDT merge: pointwise max (PVV semilattice)
47        let mut crdt_version = self.crdt_version.clone();
48        for (k, v) in &other.crdt_version {
49            crdt_version
50                .entry(*k)
51                .and_modify(|existing| *existing = (*existing).max(*v))
52                .or_insert(*v);
53        }
54
55        Self { holonomy, peer_agreement, crdt_version }
56    }
57}