Skip to main content

qualia_client_core/
guardianship.rs

1//! Bilateral guardianship — global suspended-transaction queue for M:N co-signature.
2
3use std::sync::{Mutex, OnceLock};
4
5use qualia_core_db::crdt::SuspendedTransactionQueue;
6use qualia_core_db::wal::WriteAheadLog;
7use qualia_core_db::{q_hash, NQuin};
8use serde::{Deserialize, Serialize};
9
10const MAX_RATIFIED: usize = 32;
11
12static SUSPENDED_QUEUE: OnceLock<Mutex<SuspendedTransactionQueue>> = OnceLock::new();
13static RATIFIED_IDS: OnceLock<Mutex<[Option<u64>; MAX_RATIFIED]>> = OnceLock::new();
14
15/// Suspended-transaction queue.
16pub fn suspended_queue() -> &'static Mutex<SuspendedTransactionQueue> {
17    SUSPENDED_QUEUE.get_or_init(|| Mutex::new(SuspendedTransactionQueue::new()))
18}
19
20fn ratified_ids() -> &'static Mutex<[Option<u64>; MAX_RATIFIED]> {
21    RATIFIED_IDS.get_or_init(|| Mutex::new([None; MAX_RATIFIED]))
22}
23
24fn mark_ratified(agreement_id: u64) {
25    let mut slots = ratified_ids().lock().expect("ratified_ids");
26    if slots.iter().any(|s| *s == Some(agreement_id)) {
27        return;
28    }
29    for slot in slots.iter_mut() {
30        if slot.is_none() {
31            *slot = Some(agreement_id);
32            return;
33        }
34    }
35}
36
37/// View of a suspended guardianship transaction for UI trays.
38#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct SuspendedTxView {
40    pub agreement_id: u64,
41    pub threshold: u8,
42    pub collected_signatures: u8,
43    pub subject: u64,
44    pub predicate: u64,
45    pub object: u64,
46    pub context: u64,
47    pub metadata: u64,
48    pub label: String,
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
52#[serde(rename_all = "snake_case")]
53pub enum GuardianTokenOutcome {
54    Ratified,
55    Pending,
56    Denied,
57    NotFound,
58}
59
60/// Lists pending affirmations.
61pub fn list_pending_affirmations() -> Vec<SuspendedTxView> {
62    let guard = suspended_queue().lock().expect("suspended_queue");
63    let mut out = Vec::new();
64    for slot in guard.queue.iter() {
65        if let Some(tx) = slot {
66            let q = tx.suspended_quin;
67            out.push(SuspendedTxView {
68                agreement_id: tx.agreement_id,
69                threshold: tx.threshold,
70                collected_signatures: tx.collected_signatures,
71                subject: q.subject,
72                predicate: q.predicate,
73                object: q.object,
74                context: q.context,
75                metadata: q.metadata,
76                label: format!(
77                    "Guardianship Proposal — agreement 0x{:016x}",
78                    tx.agreement_id
79                ),
80            });
81        }
82    }
83    out
84}
85
86/// Pending affirmation count.
87pub fn pending_affirmation_count() -> usize {
88    list_pending_affirmations().len()
89}
90
91/// `true` when agreement-ratified.
92pub fn is_agreement_ratified(agreement_id: u64) -> bool {
93    ratified_ids()
94        .lock()
95        .expect("ratified_ids")
96        .iter()
97        .any(|s| *s == Some(agreement_id))
98}
99
100/// Apply a guardian consent token (`q42:issuesConsentToken`) for the given agreement.
101pub fn apply_guardian_token(agreement_id: u64, token_fields: [u64; 6]) -> GuardianTokenOutcome {
102    let token = NQuin {
103        subject: token_fields[0],
104        predicate: token_fields[1],
105        object: token_fields[2],
106        context: token_fields[3],
107        metadata: token_fields[4],
108        parity: token_fields[5],
109    };
110    if token.context != agreement_id {
111        return GuardianTokenOutcome::NotFound;
112    }
113
114    let mut guard = suspended_queue().lock().expect("suspended_queue");
115    if let Some(tx) = guard.apply_consensus_token(&token) {
116        mark_ratified(agreement_id);
117        #[cfg(not(target_arch = "wasm32"))]
118        {
119            if let Ok(mut wal) = WriteAheadLog::open(".qualia_graph_mutations.wal") {
120                let mut quin = tx.suspended_quin;
121                let _ = wal.append_mutation_volatile(&mut quin);
122            }
123        }
124        GuardianTokenOutcome::Ratified
125    } else if guard.queue.iter().any(|s| {
126        s.as_ref()
127            .map(|tx| tx.agreement_id == agreement_id)
128            .unwrap_or(false)
129    }) {
130        GuardianTokenOutcome::Pending
131    } else {
132        GuardianTokenOutcome::NotFound
133    }
134}
135
136/// Build a consent token for the local principal co-signing an agreement.
137pub fn build_consent_token(agreement_id: u64, principal_hash: u64) -> [u64; 6] {
138    let q = NQuin {
139        subject: principal_hash,
140        predicate: q_hash("q42:issuesConsentToken"),
141        object: agreement_id,
142        context: agreement_id,
143        metadata: 0,
144        parity: 0,
145    };
146    [
147        q.subject,
148        q.predicate,
149        q.object,
150        q.context,
151        q.metadata,
152        q.parity,
153    ]
154}
155
156/// Remove a suspended transaction without committing to the WAL.
157pub fn deny_guardian_affirmation(agreement_id: u64) -> bool {
158    let mut guard = suspended_queue().lock().expect("suspended_queue");
159    for slot in guard.queue.iter_mut() {
160        if let Some(tx) = slot {
161            if tx.agreement_id == agreement_id {
162                *slot = None;
163                return true;
164            }
165        }
166    }
167    false
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173    use qualia_core_db::crdt::SuspendedTransaction;
174
175    #[test]
176    fn list_and_deny_pending() {
177        let queue = suspended_queue();
178        let mut guard = queue.lock().unwrap();
179        *guard = SuspendedTransactionQueue::new();
180        drop(guard);
181
182        let tx = SuspendedTransaction {
183            agreement_id: 0xABCD,
184            threshold: 2,
185            collected_signatures: 1,
186            registers: [None; 16],
187            bytecode_buffer: [None; 64],
188            yielded_op: None,
189            suspended_quin: NQuin::default(),
190        };
191        suspended_queue().lock().unwrap().push(tx).unwrap();
192
193        assert_eq!(pending_affirmation_count(), 1);
194        assert!(deny_guardian_affirmation(0xABCD));
195        assert_eq!(pending_affirmation_count(), 0);
196    }
197}